Apply spotless

This commit is contained in:
Raven Szewczyk committed 2023-01-08 17:51:39 +00:00
1 parent e1e53019e3
commit 5ce9be4671
110 files changed
+15083 -15318

No files matched your search

@@ -1,6 +1,3 @@
package me.eigenraven.lwjgl3ify;
public class Lwjgl3ify {
}
public class Lwjgl3ify {}
+204 -206
View File
@@ -46,241 +46,239 @@ import java.nio.*;
* $Id$
*/
public class BufferChecks {
/** Static methods only! */
private BufferChecks() {
}
/** Static methods only! */
private BufferChecks() {}
/**
* Helper methods to ensure a function pointer is not-null (0)
*/
public static void checkFunctionAddress(long pointer) {
if (LWJGLUtil.CHECKS && pointer == 0) {
throw new IllegalStateException("Function is not supported");
}
}
/**
* Helper methods to ensure a function pointer is not-null (0)
*/
public static void checkFunctionAddress(long pointer) {
if (LWJGLUtil.CHECKS && pointer == 0) {
throw new IllegalStateException("Function is not supported");
}
}
/**
* Helper methods to ensure a ByteBuffer is null-terminated
*/
public static void checkNullTerminated(ByteBuffer buf) {
if ( LWJGLUtil.CHECKS && buf.get(buf.limit() - 1) != 0) {
throw new IllegalArgumentException("Missing null termination");
}
}
/**
* Helper methods to ensure a ByteBuffer is null-terminated
*/
public static void checkNullTerminated(ByteBuffer buf) {
if (LWJGLUtil.CHECKS && buf.get(buf.limit() - 1) != 0) {
throw new IllegalArgumentException("Missing null termination");
}
}
public static void checkNullTerminated(ByteBuffer buf, int count) {
if ( LWJGLUtil.CHECKS ) {
int nullFound = 0;
for ( int i = buf.position(); i < buf.limit(); i++ ) {
if ( buf.get(i) == 0 )
nullFound++;
}
public static void checkNullTerminated(ByteBuffer buf, int count) {
if (LWJGLUtil.CHECKS) {
int nullFound = 0;
for (int i = buf.position(); i < buf.limit(); i++) {
if (buf.get(i) == 0) nullFound++;
}
if ( nullFound < count )
throw new IllegalArgumentException("Missing null termination");
}
}
if (nullFound < count) throw new IllegalArgumentException("Missing null termination");
}
}
/** Helper method to ensure an IntBuffer is null-terminated */
public static void checkNullTerminated(IntBuffer buf) {
if ( LWJGLUtil.CHECKS && buf.get(buf.limit() - 1) != 0 ) {
throw new IllegalArgumentException("Missing null termination");
}
}
/** Helper method to ensure an IntBuffer is null-terminated */
public static void checkNullTerminated(IntBuffer buf) {
if (LWJGLUtil.CHECKS && buf.get(buf.limit() - 1) != 0) {
throw new IllegalArgumentException("Missing null termination");
}
}
/** Helper method to ensure a LongBuffer is null-terminated */
public static void checkNullTerminated(LongBuffer buf) {
if ( LWJGLUtil.CHECKS && buf.get(buf.limit() - 1) != 0 ) {
throw new IllegalArgumentException("Missing null termination");
}
}
/** Helper method to ensure a LongBuffer is null-terminated */
public static void checkNullTerminated(LongBuffer buf) {
if (LWJGLUtil.CHECKS && buf.get(buf.limit() - 1) != 0) {
throw new IllegalArgumentException("Missing null termination");
}
}
/** Helper method to ensure a PointerBuffer is null-terminated */
public static void checkNullTerminated(PointerBuffer buf) {
if ( LWJGLUtil.CHECKS && buf.get(buf.limit() - 1) != 0 ) {
throw new IllegalArgumentException("Missing null termination");
}
}
/** Helper method to ensure a PointerBuffer is null-terminated */
public static void checkNullTerminated(PointerBuffer buf) {
if (LWJGLUtil.CHECKS && buf.get(buf.limit() - 1) != 0) {
throw new IllegalArgumentException("Missing null termination");
}
}
public static void checkNotNull(Object o) {
if ( LWJGLUtil.CHECKS && o == null)
throw new IllegalArgumentException("Null argument");
}
public static void checkNotNull(Object o) {
if (LWJGLUtil.CHECKS && o == null) throw new IllegalArgumentException("Null argument");
}
/**
* Helper methods to ensure a buffer is direct (and, implicitly, non-null).
*/
public static void checkDirect(ByteBuffer buf) {
if ( LWJGLUtil.CHECKS && !buf.isDirect()) {
throw new IllegalArgumentException("ByteBuffer is not direct");
}
}
/**
* Helper methods to ensure a buffer is direct (and, implicitly, non-null).
*/
public static void checkDirect(ByteBuffer buf) {
if (LWJGLUtil.CHECKS && !buf.isDirect()) {
throw new IllegalArgumentException("ByteBuffer is not direct");
}
}
public static void checkDirect(ShortBuffer buf) {
if ( LWJGLUtil.CHECKS && !buf.isDirect()) {
throw new IllegalArgumentException("ShortBuffer is not direct");
}
}
public static void checkDirect(ShortBuffer buf) {
if (LWJGLUtil.CHECKS && !buf.isDirect()) {
throw new IllegalArgumentException("ShortBuffer is not direct");
}
}
public static void checkDirect(IntBuffer buf) {
if ( LWJGLUtil.CHECKS && !buf.isDirect()) {
throw new IllegalArgumentException("IntBuffer is not direct");
}
}
public static void checkDirect(IntBuffer buf) {
if (LWJGLUtil.CHECKS && !buf.isDirect()) {
throw new IllegalArgumentException("IntBuffer is not direct");
}
}
public static void checkDirect(LongBuffer buf) {
if ( LWJGLUtil.CHECKS && !buf.isDirect()) {
throw new IllegalArgumentException("LongBuffer is not direct");
}
}
public static void checkDirect(LongBuffer buf) {
if (LWJGLUtil.CHECKS && !buf.isDirect()) {
throw new IllegalArgumentException("LongBuffer is not direct");
}
}
public static void checkDirect(FloatBuffer buf) {
if ( LWJGLUtil.CHECKS && !buf.isDirect()) {
throw new IllegalArgumentException("FloatBuffer is not direct");
}
}
public static void checkDirect(FloatBuffer buf) {
if (LWJGLUtil.CHECKS && !buf.isDirect()) {
throw new IllegalArgumentException("FloatBuffer is not direct");
}
}
public static void checkDirect(DoubleBuffer buf) {
if ( LWJGLUtil.CHECKS && !buf.isDirect()) {
throw new IllegalArgumentException("DoubleBuffer is not direct");
}
}
public static void checkDirect(DoubleBuffer buf) {
if (LWJGLUtil.CHECKS && !buf.isDirect()) {
throw new IllegalArgumentException("DoubleBuffer is not direct");
}
}
public static void checkDirect(PointerBuffer buf) {
// NO-OP, PointerBuffer is always direct.
}
public static void checkDirect(PointerBuffer buf) {
// NO-OP, PointerBuffer is always direct.
}
public static void checkArray(Object[] array) {
if ( LWJGLUtil.CHECKS && (array == null || array.length == 0) )
throw new IllegalArgumentException("Invalid array");
}
public static void checkArray(Object[] array) {
if (LWJGLUtil.CHECKS && (array == null || array.length == 0))
throw new IllegalArgumentException("Invalid array");
}
/**
* This is a separate call to help inline checkBufferSize.
*/
private static void throwBufferSizeException(Buffer buf, int size) {
throw new IllegalArgumentException("Number of remaining buffer elements is " + buf.remaining() + ", must be at least " + size + ". Because at most " + size + " elements can be returned, a buffer with at least " + size + " elements is required, regardless of actual returned element count");
}
/**
* This is a separate call to help inline checkBufferSize.
*/
private static void throwBufferSizeException(Buffer buf, int size) {
throw new IllegalArgumentException(
"Number of remaining buffer elements is " + buf.remaining() + ", must be at least " + size
+ ". Because at most " + size + " elements can be returned, a buffer with at least " + size
+ " elements is required, regardless of actual returned element count");
}
private static void throwBufferSizeException(PointerBuffer buf, int size) {
throw new IllegalArgumentException("Number of remaining pointer buffer elements is " + buf.remaining() + ", must be at least " + size);
}
private static void throwBufferSizeException(PointerBuffer buf, int size) {
throw new IllegalArgumentException(
"Number of remaining pointer buffer elements is " + buf.remaining() + ", must be at least " + size);
}
private static void throwArraySizeException(Object[] array, int size) {
throw new IllegalArgumentException("Number of array elements is " + array.length + ", must be at least " + size);
}
private static void throwArraySizeException(Object[] array, int size) {
throw new IllegalArgumentException(
"Number of array elements is " + array.length + ", must be at least " + size);
}
private static void throwArraySizeException(long[] array, int size) {
throw new IllegalArgumentException("Number of array elements is " + array.length + ", must be at least " + size);
}
private static void throwArraySizeException(long[] array, int size) {
throw new IllegalArgumentException(
"Number of array elements is " + array.length + ", must be at least " + size);
}
/**
* Helper method to ensure a buffer is big enough to receive data from a
* glGet* operation.
*
* @param buf
* The buffer to check
* @param size
* The minimum buffer size
* @throws IllegalArgumentException
*/
public static void checkBufferSize(Buffer buf, int size) {
if ( LWJGLUtil.CHECKS && buf.remaining() < size) {
throwBufferSizeException(buf, size);
}
}
/**
* Helper method to ensure a buffer is big enough to receive data from a
* glGet* operation.
*
* @param buf
* The buffer to check
* @param size
* The minimum buffer size
* @throws IllegalArgumentException
*/
public static void checkBufferSize(Buffer buf, int size) {
if (LWJGLUtil.CHECKS && buf.remaining() < size) {
throwBufferSizeException(buf, size);
}
}
/**
* Detects the buffer type and performs the corresponding check
* and also returns the buffer position in bytes.
*
* @param buffer the buffer to check
* @param size the size to check
*
* @return the buffer position in bytes
*/
public static int checkBuffer(final Buffer buffer, final int size) {
final int posShift;
if ( buffer instanceof ByteBuffer ) {
BufferChecks.checkBuffer((ByteBuffer)buffer, size);
posShift = 0;
} else if ( buffer instanceof ShortBuffer ) {
BufferChecks.checkBuffer((ShortBuffer)buffer, size);
posShift = 1;
} else if ( buffer instanceof IntBuffer ) {
BufferChecks.checkBuffer((IntBuffer)buffer, size);
posShift = 2;
} else if ( buffer instanceof LongBuffer ) {
BufferChecks.checkBuffer((LongBuffer)buffer, size);
posShift = 4;
} else if ( buffer instanceof FloatBuffer ) {
BufferChecks.checkBuffer((FloatBuffer)buffer, size);
posShift = 2;
} else if ( buffer instanceof DoubleBuffer ) {
BufferChecks.checkBuffer((DoubleBuffer)buffer, size);
posShift = 4;
} else
throw new IllegalArgumentException("Unsupported Buffer type specified: " + buffer.getClass());
/**
* Detects the buffer type and performs the corresponding check
* and also returns the buffer position in bytes.
*
* @param buffer the buffer to check
* @param size the size to check
*
* @return the buffer position in bytes
*/
public static int checkBuffer(final Buffer buffer, final int size) {
final int posShift;
if (buffer instanceof ByteBuffer) {
BufferChecks.checkBuffer((ByteBuffer) buffer, size);
posShift = 0;
} else if (buffer instanceof ShortBuffer) {
BufferChecks.checkBuffer((ShortBuffer) buffer, size);
posShift = 1;
} else if (buffer instanceof IntBuffer) {
BufferChecks.checkBuffer((IntBuffer) buffer, size);
posShift = 2;
} else if (buffer instanceof LongBuffer) {
BufferChecks.checkBuffer((LongBuffer) buffer, size);
posShift = 4;
} else if (buffer instanceof FloatBuffer) {
BufferChecks.checkBuffer((FloatBuffer) buffer, size);
posShift = 2;
} else if (buffer instanceof DoubleBuffer) {
BufferChecks.checkBuffer((DoubleBuffer) buffer, size);
posShift = 4;
} else throw new IllegalArgumentException("Unsupported Buffer type specified: " + buffer.getClass());
return buffer.position() << posShift;
}
return buffer.position() << posShift;
}
public static void checkBuffer(ByteBuffer buf, int size) {
if ( LWJGLUtil.CHECKS ) {
checkBufferSize(buf, size);
checkDirect(buf);
}
}
public static void checkBuffer(ByteBuffer buf, int size) {
if (LWJGLUtil.CHECKS) {
checkBufferSize(buf, size);
checkDirect(buf);
}
}
public static void checkBuffer(ShortBuffer buf, int size) {
if ( LWJGLUtil.CHECKS ) {
checkBufferSize(buf, size);
checkDirect(buf);
}
}
public static void checkBuffer(ShortBuffer buf, int size) {
if (LWJGLUtil.CHECKS) {
checkBufferSize(buf, size);
checkDirect(buf);
}
}
public static void checkBuffer(IntBuffer buf, int size) {
if ( LWJGLUtil.CHECKS ) {
checkBufferSize(buf, size);
checkDirect(buf);
}
}
public static void checkBuffer(IntBuffer buf, int size) {
if (LWJGLUtil.CHECKS) {
checkBufferSize(buf, size);
checkDirect(buf);
}
}
public static void checkBuffer(LongBuffer buf, int size) {
if ( LWJGLUtil.CHECKS ) {
checkBufferSize(buf, size);
checkDirect(buf);
}
}
public static void checkBuffer(LongBuffer buf, int size) {
if (LWJGLUtil.CHECKS) {
checkBufferSize(buf, size);
checkDirect(buf);
}
}
public static void checkBuffer(FloatBuffer buf, int size) {
if ( LWJGLUtil.CHECKS ) {
checkBufferSize(buf, size);
checkDirect(buf);
}
}
public static void checkBuffer(FloatBuffer buf, int size) {
if (LWJGLUtil.CHECKS) {
checkBufferSize(buf, size);
checkDirect(buf);
}
}
public static void checkBuffer(DoubleBuffer buf, int size) {
if ( LWJGLUtil.CHECKS ) {
checkBufferSize(buf, size);
checkDirect(buf);
}
}
public static void checkBuffer(DoubleBuffer buf, int size) {
if (LWJGLUtil.CHECKS) {
checkBufferSize(buf, size);
checkDirect(buf);
}
}
public static void checkBuffer(PointerBuffer buf, int size) {
if ( LWJGLUtil.CHECKS && buf.remaining() < size ) {
throwBufferSizeException(buf, size);
}
}
public static void checkBuffer(PointerBuffer buf, int size) {
if (LWJGLUtil.CHECKS && buf.remaining() < size) {
throwBufferSizeException(buf, size);
}
}
public static void checkArray(Object[] array, int size) {
if ( LWJGLUtil.CHECKS && array.length < size )
throwArraySizeException(array, size);
}
public static void checkArray(Object[] array, int size) {
if (LWJGLUtil.CHECKS && array.length < size) throwArraySizeException(array, size);
}
public static void checkArray(long[] array, int size) {
if ( LWJGLUtil.CHECKS && array.length < size )
throwArraySizeException(array, size);
}
}
public static void checkArray(long[] array, int size) {
if (LWJGLUtil.CHECKS && array.length < size) throwArraySizeException(array, size);
}
}
+127 -134
View File
@@ -48,158 +48,151 @@ import java.nio.ShortBuffer;
* @version $Revision: 3528 $
* $Id: BufferUtils.java 3528 2011-05-11 00:12:52Z spasi $
*/
public final class BufferUtils {
/**
* Construct a direct native-ordered bytebuffer with the specified size.
* @param size The size, in bytes
* @return a ByteBuffer
*/
public static ByteBuffer createByteBuffer(int size) {
return ByteBuffer.allocateDirect(size).order(ByteOrder.nativeOrder());
}
/**
* Construct a direct native-ordered bytebuffer with the specified size.
* @param size The size, in bytes
* @return a ByteBuffer
*/
public static ByteBuffer createByteBuffer(int size) {
return ByteBuffer.allocateDirect(size).order(ByteOrder.nativeOrder());
}
/**
* Construct a direct native-order shortbuffer with the specified number
* of elements.
* @param size The size, in shorts
* @return a ShortBuffer
*/
public static ShortBuffer createShortBuffer(int size) {
return createByteBuffer(size << 1).asShortBuffer();
}
/**
* Construct a direct native-order shortbuffer with the specified number
* of elements.
* @param size The size, in shorts
* @return a ShortBuffer
*/
public static ShortBuffer createShortBuffer(int size) {
return createByteBuffer(size << 1).asShortBuffer();
}
/**
* Construct a direct native-order charbuffer with the specified number
* of elements.
* @param size The size, in chars
* @return an CharBuffer
*/
public static CharBuffer createCharBuffer(int size) {
return createByteBuffer(size << 1).asCharBuffer();
}
/**
* Construct a direct native-order charbuffer with the specified number
* of elements.
* @param size The size, in chars
* @return an CharBuffer
*/
public static CharBuffer createCharBuffer(int size) {
return createByteBuffer(size << 1).asCharBuffer();
}
/**
* Construct a direct native-order intbuffer with the specified number
* of elements.
* @param size The size, in ints
* @return an IntBuffer
*/
public static IntBuffer createIntBuffer(int size) {
return createByteBuffer(size << 2).asIntBuffer();
}
/**
* Construct a direct native-order intbuffer with the specified number
* of elements.
* @param size The size, in ints
* @return an IntBuffer
*/
public static IntBuffer createIntBuffer(int size) {
return createByteBuffer(size << 2).asIntBuffer();
}
/**
* Construct a direct native-order longbuffer with the specified number
* of elements.
* @param size The size, in longs
* @return an LongBuffer
*/
public static LongBuffer createLongBuffer(int size) {
return createByteBuffer(size << 3).asLongBuffer();
}
/**
* Construct a direct native-order longbuffer with the specified number
* of elements.
* @param size The size, in longs
* @return an LongBuffer
*/
public static LongBuffer createLongBuffer(int size) {
return createByteBuffer(size << 3).asLongBuffer();
}
/**
* Construct a direct native-order floatbuffer with the specified number
* of elements.
* @param size The size, in floats
* @return a FloatBuffer
*/
public static FloatBuffer createFloatBuffer(int size) {
return createByteBuffer(size << 2).asFloatBuffer();
}
/**
* Construct a direct native-order floatbuffer with the specified number
* of elements.
* @param size The size, in floats
* @return a FloatBuffer
*/
public static FloatBuffer createFloatBuffer(int size) {
return createByteBuffer(size << 2).asFloatBuffer();
}
/**
* Construct a direct native-order doublebuffer with the specified number
* of elements.
* @param size The size, in floats
* @return a FloatBuffer
*/
public static DoubleBuffer createDoubleBuffer(int size) {
return createByteBuffer(size << 3).asDoubleBuffer();
}
/**
* Construct a direct native-order doublebuffer with the specified number
* of elements.
* @param size The size, in floats
* @return a FloatBuffer
*/
public static DoubleBuffer createDoubleBuffer(int size) {
return createByteBuffer(size << 3).asDoubleBuffer();
}
/**
* Construct a PointerBuffer with the specified number
* of elements.
* @param size The size, in memory addresses
* @return a PointerBuffer
*/
public static PointerBuffer createPointerBuffer(int size) {
return PointerBuffer.allocateDirect(size);
}
/**
* Construct a PointerBuffer with the specified number
* of elements.
* @param size The size, in memory addresses
* @return a PointerBuffer
*/
public static PointerBuffer createPointerBuffer(int size) {
return PointerBuffer.allocateDirect(size);
}
/**
* @return n, where buffer_element_size=2^n.
*/
public static int getElementSizeExponent(Buffer buf) {
if (buf instanceof ByteBuffer)
return 0;
else if (buf instanceof ShortBuffer || buf instanceof CharBuffer)
return 1;
else if (buf instanceof FloatBuffer || buf instanceof IntBuffer)
return 2;
else if (buf instanceof LongBuffer || buf instanceof DoubleBuffer)
return 3;
else
throw new IllegalStateException("Unsupported buffer type: " + buf);
}
/**
* @return n, where buffer_element_size=2^n.
*/
public static int getElementSizeExponent(Buffer buf) {
if (buf instanceof ByteBuffer) return 0;
else if (buf instanceof ShortBuffer || buf instanceof CharBuffer) return 1;
else if (buf instanceof FloatBuffer || buf instanceof IntBuffer) return 2;
else if (buf instanceof LongBuffer || buf instanceof DoubleBuffer) return 3;
else throw new IllegalStateException("Unsupported buffer type: " + buf);
}
/**
* A helper function which is used to get the byte offset in an arbitrary buffer
* based on its position
* @return the position of the buffer, in BYTES
*/
public static int getOffset(Buffer buffer) {
return buffer.position() << getElementSizeExponent(buffer);
}
/**
* A helper function which is used to get the byte offset in an arbitrary buffer
* based on its position
* @return the position of the buffer, in BYTES
*/
public static int getOffset(Buffer buffer) {
return buffer.position() << getElementSizeExponent(buffer);
}
/** Fill buffer with zeros from position to remaining */
public static void zeroBuffer(ByteBuffer b) {
zeroBuffer0(b, b.position(), b.remaining());
}
/** Fill buffer with zeros from position to remaining */
public static void zeroBuffer(ByteBuffer b) {
zeroBuffer0(b, b.position(), b.remaining());
}
/** Fill buffer with zeros from position to remaining */
public static void zeroBuffer(ShortBuffer b) {
zeroBuffer0(b, b.position()*2L, b.remaining()*2L);
}
/** Fill buffer with zeros from position to remaining */
public static void zeroBuffer(ShortBuffer b) {
zeroBuffer0(b, b.position() * 2L, b.remaining() * 2L);
}
/** Fill buffer with zeros from position to remaining */
public static void zeroBuffer(CharBuffer b) {
zeroBuffer0(b, b.position()*2L, b.remaining()*2L);
}
/** Fill buffer with zeros from position to remaining */
public static void zeroBuffer(CharBuffer b) {
zeroBuffer0(b, b.position() * 2L, b.remaining() * 2L);
}
/** Fill buffer with zeros from position to remaining */
public static void zeroBuffer(IntBuffer b) {
zeroBuffer0(b, b.position()*4L, b.remaining()*4L);
}
/** Fill buffer with zeros from position to remaining */
public static void zeroBuffer(IntBuffer b) {
zeroBuffer0(b, b.position() * 4L, b.remaining() * 4L);
}
/** Fill buffer with zeros from position to remaining */
public static void zeroBuffer(FloatBuffer b) {
zeroBuffer0(b, b.position()*4L, b.remaining()*4L);
}
/** Fill buffer with zeros from position to remaining */
public static void zeroBuffer(FloatBuffer b) {
zeroBuffer0(b, b.position() * 4L, b.remaining() * 4L);
}
/** Fill buffer with zeros from position to remaining */
public static void zeroBuffer(LongBuffer b) {
zeroBuffer0(b, b.position()*8L, b.remaining()*8L);
}
/** Fill buffer with zeros from position to remaining */
public static void zeroBuffer(LongBuffer b) {
zeroBuffer0(b, b.position() * 8L, b.remaining() * 8L);
}
/** Fill buffer with zeros from position to remaining */
public static void zeroBuffer(DoubleBuffer b) {
zeroBuffer0(b, b.position()*8L, b.remaining()*8L);
}
/** Fill buffer with zeros from position to remaining */
public static void zeroBuffer(DoubleBuffer b) {
zeroBuffer0(b, b.position() * 8L, b.remaining() * 8L);
}
/** Fill buffer with zeros from position to remaining */
private static native void zeroBuffer0(Buffer b, long off, long size);
/**
* Returns the memory address of the specified buffer.
*
* @param buffer the buffer
*
* @return the memory address
*/
static native long getBufferAddress(Buffer buffer);
/** Fill buffer with zeros from position to remaining */
private static native void zeroBuffer0(Buffer b, long off, long size);
/**
* Returns the memory address of the specified buffer.
*
* @param buffer the buffer
*
* @return the memory address
*/
static native long getBufferAddress(Buffer buffer);
}
+43 -43
View File
@@ -1,31 +1,31 @@
/*
/*
* Copyright (c) 2002-2008 LWJGL Project
* All rights reserved.
*
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* * Neither the name of 'LWJGL' nor the names of
* its contributors may be used to endorse or promote products derived
* * Neither the name of 'LWJGL' nor the names of
* its contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
@@ -36,44 +36,44 @@ package org.lwjglx;
* This exception is supplied to make exception handling more generic for LWJGL
* specific exceptions
* </p>
*
*
* @author Brian Matzon <[email protected]>
* @version $Revision$
* $Id$
*/
public class LWJGLException extends Exception {
private static final long serialVersionUID = 1L;
private static final long serialVersionUID = 1L;
/**
* Plain c'tor
*/
public LWJGLException() {
super();
}
/**
* Plain c'tor
*/
public LWJGLException() {
super();
}
/**
* Creates a new LWJGLException
*
* @param msg
* String identifier for exception
*/
public LWJGLException(String msg) {
super(msg);
}
/**
* Creates a new LWJGLException
*
* @param msg
* String identifier for exception
*/
public LWJGLException(String msg) {
super(msg);
}
/**
* @param message
* @param cause
*/
public LWJGLException(String message, Throwable cause) {
super(message, cause);
}
/**
* @param message
* @param cause
*/
public LWJGLException(String message, Throwable cause) {
super(message, cause);
}
/**
* @param cause
*/
public LWJGLException(Throwable cause) {
super(cause);
}
/**
* @param cause
*/
public LWJGLException(Throwable cause) {
super(cause);
}
}
File diff suppressed because it is too large. Load diff
+444 -383
View File
@@ -44,387 +44,448 @@ import java.nio.charset.*;
*/
public final class MemoryUtil {
private static final Charset ascii;
private static final Charset utf8;
private static final Charset utf16;
static {
ascii = Charset.forName("ISO-8859-1");
utf8 = Charset.forName("UTF-8");
utf16 = Charset.forName("UTF-16LE");
}
private static final Accessor memUtil;
static {
Accessor util;
try {
// Depends on java.nio.Buffer#address and sun.misc.Unsafe
util = loadAccessor("org.lwjgl.MemoryUtilSun$AccessorUnsafe");
} catch (Exception e0) {
try {
// Depends on java.nio.Buffer#address and sun.reflect.FieldAccessor
util = loadAccessor("org.lwjgl.MemoryUtilSun$AccessorReflectFast");
} catch (Exception e1) {
try {
// Depends on java.nio.Buffer#address
util = new AccessorReflect();
} catch (Exception e2) {
LWJGLUtil.log("Unsupported JVM detected, this will likely result in low performance. Please inform LWJGL developers.");
util = new AccessorJNI();
}
}
}
LWJGLUtil.log("MemoryUtil Accessor: " + util.getClass().getSimpleName());
memUtil = util;
/*
BENCHMARK RESULTS - Oracle Server VM:
Unsafe: 4ns
ReflectFast: 8ns
Reflect: 10ns
JNI: 82ns
BENCHMARK RESULTS - Oracle Client VM:
Unsafe: 5ns
ReflectFast: 81ns
Reflect: 85ns
JNI: 87ns
On non-Oracle VMs, Unsafe should be the fastest implementation as well. In the absence
of Unsafe, performance will depend on how reflection and JNI are implemented. For now
we'll go with what we see on the Oracle VM (that is, we'll prefer reflection over JNI).
*/
}
private MemoryUtil() {
}
/**
* Returns the memory address of the specified buffer. [INTERNAL USE ONLY]
*
* @param buffer the buffer
*
* @return the memory address
*/
public static long getAddress0(Buffer buffer) { return memUtil.getAddress(buffer); }
public static long getAddress0Safe(Buffer buffer) { return buffer == null ? 0L : memUtil.getAddress(buffer); }
public static long getAddress0(PointerBuffer buffer) { return memUtil.getAddress(buffer.getBuffer()); }
public static long getAddress0Safe(PointerBuffer buffer) { return buffer == null ? 0L : memUtil.getAddress(buffer.getBuffer()); }
// --- [ API utilities ] ---
public static long getAddress(ByteBuffer buffer) { return getAddress(buffer, buffer.position()); }
public static long getAddress(ByteBuffer buffer, int position) { return getAddress0(buffer) + position; }
public static long getAddress(ShortBuffer buffer) { return getAddress(buffer, buffer.position()); }
public static long getAddress(ShortBuffer buffer, int position) { return getAddress0(buffer) + (position << 1); }
public static long getAddress(CharBuffer buffer) { return getAddress(buffer, buffer.position()); }
public static long getAddress(CharBuffer buffer, int position) { return getAddress0(buffer) + (position << 1); }
public static long getAddress(IntBuffer buffer) { return getAddress(buffer, buffer.position()); }
public static long getAddress(IntBuffer buffer, int position) { return getAddress0(buffer) + (position << 2); }
public static long getAddress(FloatBuffer buffer) { return getAddress(buffer, buffer.position()); }
public static long getAddress(FloatBuffer buffer, int position) { return getAddress0(buffer) + (position << 2); }
public static long getAddress(LongBuffer buffer) { return getAddress(buffer, buffer.position()); }
public static long getAddress(LongBuffer buffer, int position) { return getAddress0(buffer) + (position << 3); }
public static long getAddress(DoubleBuffer buffer) { return getAddress(buffer, buffer.position()); }
public static long getAddress(DoubleBuffer buffer, int position) { return getAddress0(buffer) + (position << 3); }
public static long getAddress(PointerBuffer buffer) { return getAddress(buffer, buffer.position()); }
public static long getAddress(PointerBuffer buffer, int position) { return getAddress0(buffer) + (position * PointerBuffer.getPointerSize()); }
// --- [ API utilities - Safe ] ---
public static long getAddressSafe(ByteBuffer buffer) { return buffer == null ? 0L : getAddress(buffer); }
public static long getAddressSafe(ByteBuffer buffer, int position) { return buffer == null ? 0L : getAddress(buffer, position); }
public static long getAddressSafe(ShortBuffer buffer) { return buffer == null ? 0L : getAddress(buffer); }
public static long getAddressSafe(ShortBuffer buffer, int position) { return buffer == null ? 0L : getAddress(buffer, position); }
public static long getAddressSafe(CharBuffer buffer) { return buffer == null ? 0L : getAddress(buffer); }
public static long getAddressSafe(CharBuffer buffer, int position) { return buffer == null ? 0L : getAddress(buffer, position); }
public static long getAddressSafe(IntBuffer buffer) { return buffer == null ? 0L : getAddress(buffer); }
public static long getAddressSafe(IntBuffer buffer, int position) { return buffer == null ? 0L : getAddress(buffer, position); }
public static long getAddressSafe(FloatBuffer buffer) { return buffer == null ? 0L : getAddress(buffer); }
public static long getAddressSafe(FloatBuffer buffer, int position) { return buffer == null ? 0L : getAddress(buffer, position); }
public static long getAddressSafe(LongBuffer buffer) { return buffer == null ? 0L : getAddress(buffer); }
public static long getAddressSafe(LongBuffer buffer, int position) { return buffer == null ? 0L : getAddress(buffer, position); }
public static long getAddressSafe(DoubleBuffer buffer) { return buffer == null ? 0L : getAddress(buffer); }
public static long getAddressSafe(DoubleBuffer buffer, int position) { return buffer == null ? 0L : getAddress(buffer, position); }
public static long getAddressSafe(PointerBuffer buffer) { return buffer == null ? 0L : getAddress(buffer); }
public static long getAddressSafe(PointerBuffer buffer, int position) { return buffer == null ? 0L : getAddress(buffer, position); }
// --- [ String utilities ] ---
/**
* Returns a ByteBuffer containing the specified text ASCII encoded and null-terminated.
* If text is null, null is returned.
*
* @param text the text to encode
*
* @return the encoded text or null
*
* @see String#getBytes()
*/
public static ByteBuffer encodeASCII(final CharSequence text) {
return encode(text, ascii);
}
/**
* Returns a ByteBuffer containing the specified text UTF-8 encoded and null-terminated.
* If text is null, null is returned.
*
* @param text the text to encode
*
* @return the encoded text or null
*
* @see String#getBytes()
*/
public static ByteBuffer encodeUTF8(final CharSequence text) {
return encode(text, utf8);
}
/**
* Returns a ByteBuffer containing the specified text UTF-16LE encoded and null-terminated.
* If text is null, null is returned.
*
* @param text the text to encode
*
* @return the encoded text
*/
public static ByteBuffer encodeUTF16(final CharSequence text) {
return encode(text, utf16);
}
/**
* Wraps the specified text in a null-terminated CharBuffer and encodes it using the specified Charset.
*
* @param text the text to encode
* @param charset the charset to use for encoding
*
* @return the encoded text
*/
private static ByteBuffer encode(final CharSequence text, final Charset charset) {
if ( text == null )
return null;
return encode(CharBuffer.wrap(new CharSequenceNT(text)), charset);
}
/**
* A {@link CharsetEncoder#encode(java.nio.CharBuffer)} implementation that uses {@link BufferUtils#createByteBuffer(int)}
* instead of {@link ByteBuffer#allocate(int)}.
*
* @see CharsetEncoder#encode(java.nio.CharBuffer)
*/
private static ByteBuffer encode(final CharBuffer in, final Charset charset) {
final CharsetEncoder encoder = charset.newEncoder(); // encoders are not thread-safe, create a new one on every call
int n = (int)(in.remaining() * encoder.averageBytesPerChar());
ByteBuffer out = BufferUtils.createByteBuffer(n);
if ( n == 0 && in.remaining() == 0 )
return out;
encoder.reset();
while ( true ) {
CoderResult cr = in.hasRemaining() ? encoder.encode(in, out, true) : CoderResult.UNDERFLOW;
if ( cr.isUnderflow() )
cr = encoder.flush(out);
if ( cr.isUnderflow() )
break;
if ( cr.isOverflow() ) {
n = 2 * n + 1; // Ensure progress; n might be 0!
ByteBuffer o = BufferUtils.createByteBuffer(n);
out.flip();
o.put(out);
out = o;
continue;
}
try {
cr.throwException();
} catch (CharacterCodingException e) {
throw new RuntimeException(e);
}
}
out.flip();
return out;
}
public static String decodeASCII(final ByteBuffer buffer) {
return decode(buffer, ascii);
}
public static String decodeUTF8(final ByteBuffer buffer) {
return decode(buffer, utf8);
}
public static String decodeUTF16(final ByteBuffer buffer) {
return decode(buffer, utf16);
}
private static String decode(final ByteBuffer buffer, final Charset charset) {
if ( buffer == null )
return null;
return decodeImpl(buffer, charset);
}
private static String decodeImpl(final ByteBuffer in, final Charset charset) {
final CharsetDecoder decoder = charset.newDecoder(); // decoders are not thread-safe, create a new one on every call
int n = (int)(in.remaining() * decoder.averageCharsPerByte());
CharBuffer out = BufferUtils.createCharBuffer(n);
if ( (n == 0) && (in.remaining() == 0) )
return "";
decoder.reset();
for (; ; ) {
CoderResult cr = in.hasRemaining() ? decoder.decode(in, out, true) : CoderResult.UNDERFLOW;
if ( cr.isUnderflow() )
cr = decoder.flush(out);
if ( cr.isUnderflow() )
break;
if ( cr.isOverflow() ) {
n = 2 * n + 1; // Ensure progress; n might be 0!
CharBuffer o = BufferUtils.createCharBuffer(n);
out.flip();
o.put(out);
out = o;
continue;
}
try {
cr.throwException();
} catch (CharacterCodingException e) {
throw new RuntimeException(e);
}
}
out.flip();
return out.toString();
}
/** A null-terminated CharSequence. */
private static class CharSequenceNT implements CharSequence {
final CharSequence source;
CharSequenceNT(CharSequence source) {
this.source = source;
}
public int length() {
return source.length() + 1;
}
public char charAt(final int index) {
return index == source.length() ? '\0' : source.charAt(index);
}
public CharSequence subSequence(final int start, final int end) {
return new CharSequenceNT(source.subSequence(start, Math.min(end, source.length())));
}
}
interface Accessor {
long getAddress(Buffer buffer);
}
private static Accessor loadAccessor(final String className) throws Exception {
return (Accessor)Class.forName(className).newInstance();
}
/** Default implementation. */
private static class AccessorJNI implements Accessor {
public long getAddress(final Buffer buffer) {
return BufferUtils.getBufferAddress(buffer);
}
}
/** Implementation using reflection on ByteBuffer. */
private static class AccessorReflect implements Accessor {
private final Field address;
AccessorReflect() {
try {
address = getAddressField();
} catch (NoSuchFieldException e) {
throw new UnsupportedOperationException(e);
}
address.setAccessible(true);
}
public long getAddress(final Buffer buffer) {
try {
return address.getLong(buffer);
} catch (IllegalAccessException e) {
// cannot happen
return 0L;
}
}
}
static Field getAddressField() throws NoSuchFieldException {
return getDeclaredFieldRecursive(ByteBuffer.class, "address");
}
private static Field getDeclaredFieldRecursive(final Class<?> root, final String fieldName) throws NoSuchFieldException {
Class<?> type = root;
do {
try {
return type.getDeclaredField(fieldName);
} catch (NoSuchFieldException e) {
type = type.getSuperclass();
}
} while ( type != null );
throw new NoSuchFieldException(fieldName + " does not exist in " + root.getSimpleName() + " or any of its superclasses.");
}
private static final Charset ascii;
private static final Charset utf8;
private static final Charset utf16;
static {
ascii = Charset.forName("ISO-8859-1");
utf8 = Charset.forName("UTF-8");
utf16 = Charset.forName("UTF-16LE");
}
private static final Accessor memUtil;
static {
Accessor util;
try {
// Depends on java.nio.Buffer#address and sun.misc.Unsafe
util = loadAccessor("org.lwjgl.MemoryUtilSun$AccessorUnsafe");
} catch (Exception e0) {
try {
// Depends on java.nio.Buffer#address and sun.reflect.FieldAccessor
util = loadAccessor("org.lwjgl.MemoryUtilSun$AccessorReflectFast");
} catch (Exception e1) {
try {
// Depends on java.nio.Buffer#address
util = new AccessorReflect();
} catch (Exception e2) {
LWJGLUtil.log(
"Unsupported JVM detected, this will likely result in low performance. Please inform LWJGL developers.");
util = new AccessorJNI();
}
}
}
LWJGLUtil.log("MemoryUtil Accessor: " + util.getClass().getSimpleName());
memUtil = util;
/*
BENCHMARK RESULTS - Oracle Server VM:
Unsafe: 4ns
ReflectFast: 8ns
Reflect: 10ns
JNI: 82ns
BENCHMARK RESULTS - Oracle Client VM:
Unsafe: 5ns
ReflectFast: 81ns
Reflect: 85ns
JNI: 87ns
On non-Oracle VMs, Unsafe should be the fastest implementation as well. In the absence
of Unsafe, performance will depend on how reflection and JNI are implemented. For now
we'll go with what we see on the Oracle VM (that is, we'll prefer reflection over JNI).
*/
}
private MemoryUtil() {}
/**
* Returns the memory address of the specified buffer. [INTERNAL USE ONLY]
*
* @param buffer the buffer
*
* @return the memory address
*/
public static long getAddress0(Buffer buffer) {
return memUtil.getAddress(buffer);
}
public static long getAddress0Safe(Buffer buffer) {
return buffer == null ? 0L : memUtil.getAddress(buffer);
}
public static long getAddress0(PointerBuffer buffer) {
return memUtil.getAddress(buffer.getBuffer());
}
public static long getAddress0Safe(PointerBuffer buffer) {
return buffer == null ? 0L : memUtil.getAddress(buffer.getBuffer());
}
// --- [ API utilities ] ---
public static long getAddress(ByteBuffer buffer) {
return getAddress(buffer, buffer.position());
}
public static long getAddress(ByteBuffer buffer, int position) {
return getAddress0(buffer) + position;
}
public static long getAddress(ShortBuffer buffer) {
return getAddress(buffer, buffer.position());
}
public static long getAddress(ShortBuffer buffer, int position) {
return getAddress0(buffer) + (position << 1);
}
public static long getAddress(CharBuffer buffer) {
return getAddress(buffer, buffer.position());
}
public static long getAddress(CharBuffer buffer, int position) {
return getAddress0(buffer) + (position << 1);
}
public static long getAddress(IntBuffer buffer) {
return getAddress(buffer, buffer.position());
}
public static long getAddress(IntBuffer buffer, int position) {
return getAddress0(buffer) + (position << 2);
}
public static long getAddress(FloatBuffer buffer) {
return getAddress(buffer, buffer.position());
}
public static long getAddress(FloatBuffer buffer, int position) {
return getAddress0(buffer) + (position << 2);
}
public static long getAddress(LongBuffer buffer) {
return getAddress(buffer, buffer.position());
}
public static long getAddress(LongBuffer buffer, int position) {
return getAddress0(buffer) + (position << 3);
}
public static long getAddress(DoubleBuffer buffer) {
return getAddress(buffer, buffer.position());
}
public static long getAddress(DoubleBuffer buffer, int position) {
return getAddress0(buffer) + (position << 3);
}
public static long getAddress(PointerBuffer buffer) {
return getAddress(buffer, buffer.position());
}
public static long getAddress(PointerBuffer buffer, int position) {
return getAddress0(buffer) + (position * PointerBuffer.getPointerSize());
}
// --- [ API utilities - Safe ] ---
public static long getAddressSafe(ByteBuffer buffer) {
return buffer == null ? 0L : getAddress(buffer);
}
public static long getAddressSafe(ByteBuffer buffer, int position) {
return buffer == null ? 0L : getAddress(buffer, position);
}
public static long getAddressSafe(ShortBuffer buffer) {
return buffer == null ? 0L : getAddress(buffer);
}
public static long getAddressSafe(ShortBuffer buffer, int position) {
return buffer == null ? 0L : getAddress(buffer, position);
}
public static long getAddressSafe(CharBuffer buffer) {
return buffer == null ? 0L : getAddress(buffer);
}
public static long getAddressSafe(CharBuffer buffer, int position) {
return buffer == null ? 0L : getAddress(buffer, position);
}
public static long getAddressSafe(IntBuffer buffer) {
return buffer == null ? 0L : getAddress(buffer);
}
public static long getAddressSafe(IntBuffer buffer, int position) {
return buffer == null ? 0L : getAddress(buffer, position);
}
public static long getAddressSafe(FloatBuffer buffer) {
return buffer == null ? 0L : getAddress(buffer);
}
public static long getAddressSafe(FloatBuffer buffer, int position) {
return buffer == null ? 0L : getAddress(buffer, position);
}
public static long getAddressSafe(LongBuffer buffer) {
return buffer == null ? 0L : getAddress(buffer);
}
public static long getAddressSafe(LongBuffer buffer, int position) {
return buffer == null ? 0L : getAddress(buffer, position);
}
public static long getAddressSafe(DoubleBuffer buffer) {
return buffer == null ? 0L : getAddress(buffer);
}
public static long getAddressSafe(DoubleBuffer buffer, int position) {
return buffer == null ? 0L : getAddress(buffer, position);
}
public static long getAddressSafe(PointerBuffer buffer) {
return buffer == null ? 0L : getAddress(buffer);
}
public static long getAddressSafe(PointerBuffer buffer, int position) {
return buffer == null ? 0L : getAddress(buffer, position);
}
// --- [ String utilities ] ---
/**
* Returns a ByteBuffer containing the specified text ASCII encoded and null-terminated.
* If text is null, null is returned.
*
* @param text the text to encode
*
* @return the encoded text or null
*
* @see String#getBytes()
*/
public static ByteBuffer encodeASCII(final CharSequence text) {
return encode(text, ascii);
}
/**
* Returns a ByteBuffer containing the specified text UTF-8 encoded and null-terminated.
* If text is null, null is returned.
*
* @param text the text to encode
*
* @return the encoded text or null
*
* @see String#getBytes()
*/
public static ByteBuffer encodeUTF8(final CharSequence text) {
return encode(text, utf8);
}
/**
* Returns a ByteBuffer containing the specified text UTF-16LE encoded and null-terminated.
* If text is null, null is returned.
*
* @param text the text to encode
*
* @return the encoded text
*/
public static ByteBuffer encodeUTF16(final CharSequence text) {
return encode(text, utf16);
}
/**
* Wraps the specified text in a null-terminated CharBuffer and encodes it using the specified Charset.
*
* @param text the text to encode
* @param charset the charset to use for encoding
*
* @return the encoded text
*/
private static ByteBuffer encode(final CharSequence text, final Charset charset) {
if (text == null) return null;
return encode(CharBuffer.wrap(new CharSequenceNT(text)), charset);
}
/**
* A {@link CharsetEncoder#encode(java.nio.CharBuffer)} implementation that uses {@link BufferUtils#createByteBuffer(int)}
* instead of {@link ByteBuffer#allocate(int)}.
*
* @see CharsetEncoder#encode(java.nio.CharBuffer)
*/
private static ByteBuffer encode(final CharBuffer in, final Charset charset) {
final CharsetEncoder encoder =
charset.newEncoder(); // encoders are not thread-safe, create a new one on every call
int n = (int) (in.remaining() * encoder.averageBytesPerChar());
ByteBuffer out = BufferUtils.createByteBuffer(n);
if (n == 0 && in.remaining() == 0) return out;
encoder.reset();
while (true) {
CoderResult cr = in.hasRemaining() ? encoder.encode(in, out, true) : CoderResult.UNDERFLOW;
if (cr.isUnderflow()) cr = encoder.flush(out);
if (cr.isUnderflow()) break;
if (cr.isOverflow()) {
n = 2 * n + 1; // Ensure progress; n might be 0!
ByteBuffer o = BufferUtils.createByteBuffer(n);
out.flip();
o.put(out);
out = o;
continue;
}
try {
cr.throwException();
} catch (CharacterCodingException e) {
throw new RuntimeException(e);
}
}
out.flip();
return out;
}
public static String decodeASCII(final ByteBuffer buffer) {
return decode(buffer, ascii);
}
public static String decodeUTF8(final ByteBuffer buffer) {
return decode(buffer, utf8);
}
public static String decodeUTF16(final ByteBuffer buffer) {
return decode(buffer, utf16);
}
private static String decode(final ByteBuffer buffer, final Charset charset) {
if (buffer == null) return null;
return decodeImpl(buffer, charset);
}
private static String decodeImpl(final ByteBuffer in, final Charset charset) {
final CharsetDecoder decoder =
charset.newDecoder(); // decoders are not thread-safe, create a new one on every call
int n = (int) (in.remaining() * decoder.averageCharsPerByte());
CharBuffer out = BufferUtils.createCharBuffer(n);
if ((n == 0) && (in.remaining() == 0)) return "";
decoder.reset();
for (; ; ) {
CoderResult cr = in.hasRemaining() ? decoder.decode(in, out, true) : CoderResult.UNDERFLOW;
if (cr.isUnderflow()) cr = decoder.flush(out);
if (cr.isUnderflow()) break;
if (cr.isOverflow()) {
n = 2 * n + 1; // Ensure progress; n might be 0!
CharBuffer o = BufferUtils.createCharBuffer(n);
out.flip();
o.put(out);
out = o;
continue;
}
try {
cr.throwException();
} catch (CharacterCodingException e) {
throw new RuntimeException(e);
}
}
out.flip();
return out.toString();
}
/** A null-terminated CharSequence. */
private static class CharSequenceNT implements CharSequence {
final CharSequence source;
CharSequenceNT(CharSequence source) {
this.source = source;
}
public int length() {
return source.length() + 1;
}
public char charAt(final int index) {
return index == source.length() ? '\0' : source.charAt(index);
}
public CharSequence subSequence(final int start, final int end) {
return new CharSequenceNT(source.subSequence(start, Math.min(end, source.length())));
}
}
interface Accessor {
long getAddress(Buffer buffer);
}
private static Accessor loadAccessor(final String className) throws Exception {
return (Accessor) Class.forName(className).newInstance();
}
/** Default implementation. */
private static class AccessorJNI implements Accessor {
public long getAddress(final Buffer buffer) {
return BufferUtils.getBufferAddress(buffer);
}
}
/** Implementation using reflection on ByteBuffer. */
private static class AccessorReflect implements Accessor {
private final Field address;
AccessorReflect() {
try {
address = getAddressField();
} catch (NoSuchFieldException e) {
throw new UnsupportedOperationException(e);
}
address.setAccessible(true);
}
public long getAddress(final Buffer buffer) {
try {
return address.getLong(buffer);
} catch (IllegalAccessException e) {
// cannot happen
return 0L;
}
}
}
static Field getAddressField() throws NoSuchFieldException {
return getDeclaredFieldRecursive(ByteBuffer.class, "address");
}
private static Field getDeclaredFieldRecursive(final Class<?> root, final String fieldName)
throws NoSuchFieldException {
Class<?> type = root;
do {
try {
return type.getDeclaredField(fieldName);
} catch (NoSuchFieldException e) {
type = type.getSuperclass();
}
} while (type != null);
throw new NoSuchFieldException(
fieldName + " does not exist in " + root.getSimpleName() + " or any of its superclasses.");
}
}
File diff suppressed because it is too large. Load diff
+2 -3
View File
@@ -38,6 +38,5 @@ package org.lwjglx;
*/
public interface PointerWrapper {
long getPointer();
}
long getPointer();
}
@@ -38,55 +38,56 @@ package org.lwjglx;
*/
public abstract class PointerWrapperAbstract implements PointerWrapper {
protected final long pointer;
protected final long pointer;
protected PointerWrapperAbstract(final long pointer) {
this.pointer = pointer;
}
protected PointerWrapperAbstract(final long pointer) {
this.pointer = pointer;
}
/**
* Returns true if this object represents a valid pointer.
* The pointer might be invalid because it is NULL or because
* some other action has deleted the object that this pointer
* represents.
*
* @return true if the pointer is valid
*/
public boolean isValid() {
return pointer != 0;
}
/**
* Returns true if this object represents a valid pointer.
* The pointer might be invalid because it is NULL or because
* some other action has deleted the object that this pointer
* represents.
*
* @return true if the pointer is valid
*/
public boolean isValid() {
return pointer != 0;
}
/**
* Checks if the pointer is valid and throws an IllegalStateException if
* it is not. This method is a NO-OP, unless the org.lwjgl.util.Debug
* property has been set to true.
*/
public final void checkValid() {
if ( LWJGLUtil.DEBUG && !isValid() )
throw new IllegalStateException("This " + getClass().getSimpleName() + " pointer is not valid.");
}
/**
* Checks if the pointer is valid and throws an IllegalStateException if
* it is not. This method is a NO-OP, unless the org.lwjgl.util.Debug
* property has been set to true.
*/
public final void checkValid() {
if (LWJGLUtil.DEBUG && !isValid())
throw new IllegalStateException("This " + getClass().getSimpleName() + " pointer is not valid.");
}
public final long getPointer() {
checkValid();
return pointer;
}
public final long getPointer() {
checkValid();
return pointer;
}
public boolean equals(final Object o) {
if ( this == o ) return true;
if ( !(o instanceof PointerWrapperAbstract) ) return false;
public boolean equals(final Object o) {
if (this == o) return true;
if (!(o instanceof PointerWrapperAbstract)) return false;
final PointerWrapperAbstract that = (PointerWrapperAbstract)o;
final PointerWrapperAbstract that = (PointerWrapperAbstract) o;
if ( pointer != that.pointer ) return false;
if (pointer != that.pointer) return false;
return true;
}
return true;
}
public int hashCode() {
return (int)(pointer ^ (pointer >>> 32));
}
public int hashCode() {
return (int) (pointer ^ (pointer >>> 32));
}
public String toString() {
return getClass().getSimpleName() + " pointer (0x" + Long.toHexString(pointer).toUpperCase() + ")";
}
}
public String toString() {
return getClass().getSimpleName() + " pointer (0x"
+ Long.toHexString(pointer).toUpperCase() + ")";
}
}
+50 -56
View File
@@ -2,76 +2,70 @@ package org.lwjglx;
import static org.lwjgl.glfw.GLFW.glfwInit;
import org.lwjgl.opengl.GL11;
import org.lwjgl.glfw.GLFW;
import java.awt.Desktop;
import java.net.URI;
import javax.swing.JOptionPane;
import javax.swing.UIManager;
import org.lwjgl.glfw.GLFW;
public class Sys {
static {
if ( !glfwInit() )
throw new IllegalStateException("Unable to initialize glfw");
}
public static void initialize() {
static {
if (!glfwInit()) throw new IllegalStateException("Unable to initialize glfw");
}
}
public static void initialize() {}
/** Returns the LWJGL version. */
public static String getVersion() {
return org.lwjgl.Sys.getVersion();
}
/** Returns the LWJGL version. */
public static String getVersion() {
return org.lwjgl.Sys.getVersion();
}
/**
* Obtains the number of ticks that the hires timer does in a second. This method is fast;
* it should be called as frequently as possible, as it recalibrates the timer.
*
* @return timer resolution in ticks per second or 0 if no timer is present.
*/
public static long getTimerResolution() {
return 1000;
}
/**
* Obtains the number of ticks that the hires timer does in a second. This method is fast;
* it should be called as frequently as possible, as it recalibrates the timer.
*
* @return timer resolution in ticks per second or 0 if no timer is present.
*/
public static long getTimerResolution() {
return 1000;
}
/**
* Gets the current value of the hires timer, in ticks. When the Sys class is first loaded
* the hires timer is reset to 0. If no hires timer is present then this method will always
* return 0.<p><strong>NOTEZ BIEN</strong> that the hires timer WILL wrap around.
*
* @return the current hires time, in ticks (always >= 0)
*/
public static long getTime() {
return (long) (GLFW.glfwGetTime() * 1000);
}
/**
* Gets the current value of the hires timer, in ticks. When the Sys class is first loaded
* the hires timer is reset to 0. If no hires timer is present then this method will always
* return 0.<p><strong>NOTEZ BIEN</strong> that the hires timer WILL wrap around.
*
* @return the current hires time, in ticks (always >= 0)
*/
public static long getTime() {
return (long) (GLFW.glfwGetTime() * 1000);
}
public static long getNanoTime() {
return (long) (GLFW.glfwGetTime() * (1000L * 1000L * 1000L));
}
public static long getNanoTime() {
return (long) (GLFW.glfwGetTime() * (1000L * 1000L * 1000L));
}
public static boolean openURL(String url) {
if (!Desktop.isDesktopSupported()) return false;
public static boolean openURL(String url) {
if (!Desktop.isDesktopSupported()) return false;
Desktop desktop = Desktop.getDesktop();
if (!desktop.isSupported(Desktop.Action.BROWSE)) return false;
Desktop desktop = Desktop.getDesktop();
if (!desktop.isSupported(Desktop.Action.BROWSE)) return false;
try {
desktop.browse(new URI(url));
return true;
} catch (Exception ex) {
return false;
}
}
try {
desktop.browse(new URI(url));
return true;
} catch (Exception ex) {
return false;
}
}
public static void alert(String title, String message) {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch(Exception e) {
LWJGLUtil.log("Caught exception while setting LAF: " + e);
}
JOptionPane.showMessageDialog(null, message, title, JOptionPane.WARNING_MESSAGE);
}
public static void alert(String title, String message) {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (Exception e) {
LWJGLUtil.log("Caught exception while setting LAF: " + e);
}
JOptionPane.showMessageDialog(null, message, title, JOptionPane.WARNING_MESSAGE);
}
}
+185 -189
View File
@@ -32,12 +32,7 @@
package org.lwjglx.input;
import java.nio.IntBuffer;
import org.lwjglx.BufferChecks;
import org.lwjglx.BufferUtils;
import org.lwjglx.LWJGLException;
import org.lwjglx.LWJGLUtil;
import org.lwjglx.Sys;
/**
*
@@ -48,211 +43,212 @@ import org.lwjglx.Sys;
* @version $Revision$
* $Id$
*/
public class Cursor {
/** 1 bit transparency for native cursor */
public static final int CURSOR_ONE_BIT_TRANSPARENCY = 1;
/** 1 bit transparency for native cursor */
public static final int CURSOR_ONE_BIT_TRANSPARENCY = 1;
/** 8 bit alhpa native cursor */
public static final int CURSOR_8_BIT_ALPHA = 2;
/** 8 bit alhpa native cursor */
public static final int CURSOR_8_BIT_ALPHA = 2;
/** animation native cursor */
public static final int CURSOR_ANIMATION = 4;
/** animation native cursor */
public static final int CURSOR_ANIMATION = 4;
/** First element to display */
private final CursorElement[] cursors;
/** First element to display */
private final CursorElement[] cursors;
/** Index into list of cursors */
private int index;
/** Index into list of cursors */
private int index;
private boolean destroyed;
private boolean destroyed;
/**
* Constructs a new Cursor, with the given parameters. Mouse must have been created before you can create
* Cursor objects. Cursor images are in ARGB format, but only one bit transparancy is guaranteed to be supported.
* So to maximize portability, lwjgl applications should only create cursor images with 0x00 or 0xff as alpha values.
* The constructor will copy the images and delays, so there's no need to keep them around.
*
* @param width cursor image width
* @param height cursor image height
* @param xHotspot the x coordinate of the cursor hotspot
* @param yHotspot the y coordinate of the cursor hotspot
* @param numImages number of cursor images specified. Must be 1 if animations are not supported.
* @param images A buffer containing the images. The origin is at the lower left corner, like OpenGL.
* @param delays An int buffer of animation frame delays, if numImages is greater than 1, else null
* @throws LWJGLException if the cursor could not be created for any reason
*/
public Cursor(int width, int height, int xHotspot, int yHotspot, int numImages, IntBuffer images, IntBuffer delays) throws LWJGLException {
// TODO
cursors = null;
}
/**
* Constructs a new Cursor, with the given parameters. Mouse must have been created before you can create
* Cursor objects. Cursor images are in ARGB format, but only one bit transparancy is guaranteed to be supported.
* So to maximize portability, lwjgl applications should only create cursor images with 0x00 or 0xff as alpha values.
* The constructor will copy the images and delays, so there's no need to keep them around.
*
* @param width cursor image width
* @param height cursor image height
* @param xHotspot the x coordinate of the cursor hotspot
* @param yHotspot the y coordinate of the cursor hotspot
* @param numImages number of cursor images specified. Must be 1 if animations are not supported.
* @param images A buffer containing the images. The origin is at the lower left corner, like OpenGL.
* @param delays An int buffer of animation frame delays, if numImages is greater than 1, else null
* @throws LWJGLException if the cursor could not be created for any reason
*/
public Cursor(int width, int height, int xHotspot, int yHotspot, int numImages, IntBuffer images, IntBuffer delays)
throws LWJGLException {
// TODO
cursors = null;
}
/**
* Gets the minimum size of a native cursor. Can only be called if
* The Mouse is created and cursor caps includes at least
* CURSOR_ONE_BIT_TRANSPARANCY.
*
* @return the maximum size of a native cursor
*/
public static int getMinCursorSize() {
// TODO
return 0;
}
/**
* Gets the minimum size of a native cursor. Can only be called if
* The Mouse is created and cursor caps includes at least
* CURSOR_ONE_BIT_TRANSPARANCY.
*
* @return the maximum size of a native cursor
*/
public static int getMinCursorSize() {
// TODO
return 0;
}
/**
* Gets the maximum size of a native cursor. Can only be called if
* The Mouse is created and cursor caps includes at least
* CURSOR_ONE_BIT_TRANSPARANCY.
*
* @return the maximum size of a native cursor
*/
public static int getMaxCursorSize() {
// TODO
return 0;
}
/**
* Gets the maximum size of a native cursor. Can only be called if
* The Mouse is created and cursor caps includes at least
* CURSOR_ONE_BIT_TRANSPARANCY.
*
* @return the maximum size of a native cursor
*/
public static int getMaxCursorSize() {
// TODO
return 0;
}
/**
* Get the capabilities of the native cursor. Return a bit mask of the native cursor capabilities.
* The CURSOR_ONE_BIT_TRANSPARANCY indicates support for cursors with one bit transparancy,
* the CURSOR_8_BIT_ALPHA indicates support for 8 bit alpha and CURSOR_ANIMATION indicates
* support for cursor animations.
*
* @return A bit mask with native cursor capabilities.
*/
public static int getCapabilities() {
// TODO
return 0;
}
/**
* Get the capabilities of the native cursor. Return a bit mask of the native cursor capabilities.
* The CURSOR_ONE_BIT_TRANSPARANCY indicates support for cursors with one bit transparancy,
* the CURSOR_8_BIT_ALPHA indicates support for 8 bit alpha and CURSOR_ANIMATION indicates
* support for cursor animations.
*
* @return A bit mask with native cursor capabilities.
*/
public static int getCapabilities() {
// TODO
return 0;
}
/**
* Creates the actual cursor, using a platform specific class
*/
private static CursorElement[] createCursors(int width, int height, int xHotspot, int yHotspot, int numImages, IntBuffer images, IntBuffer delays) throws LWJGLException {
// TODO
return null;
}
/**
* Convert an IntBuffer image of ARGB format into ABGR
*
* @param imageBuffer image to convert
*/
private static void convertARGBtoABGR(IntBuffer imageBuffer) {
for (int i = 0; i < imageBuffer.limit(); i++) {
int argbColor = imageBuffer.get(i);
byte alpha = (byte)(argbColor >>> 24);
byte blue = (byte)(argbColor >>> 16);
byte green = (byte)(argbColor >>> 8);
byte red = (byte)argbColor;
int abgrColor = ((alpha & 0xff) << 24 ) + ((red & 0xff) << 16 ) + ((green & 0xff) << 8 ) + ((blue & 0xff) );
imageBuffer.put(i, abgrColor);
}
}
/**
* Creates the actual cursor, using a platform specific class
*/
private static CursorElement[] createCursors(
int width, int height, int xHotspot, int yHotspot, int numImages, IntBuffer images, IntBuffer delays)
throws LWJGLException {
// TODO
return null;
}
/**
* Flips the images so they're oriented according to opengl
*
* @param width Width of image
* @param height Height of images
* @param numImages How many images to flip
* @param images Source images
* @param images_copy Destination images
*/
private static void flipImages(int width, int height, int numImages, IntBuffer images, IntBuffer images_copy) {
for (int i = 0; i < numImages; i++) {
int start_index = i*width*height;
flipImage(width, height, start_index, images, images_copy);
}
}
/**
* Convert an IntBuffer image of ARGB format into ABGR
*
* @param imageBuffer image to convert
*/
private static void convertARGBtoABGR(IntBuffer imageBuffer) {
for (int i = 0; i < imageBuffer.limit(); i++) {
int argbColor = imageBuffer.get(i);
/**
* @param width Width of image
* @param height Height of images
* @param start_index index into source buffer to copy to
* @param images Source images
* @param images_copy Destination images
*/
private static void flipImage(int width, int height, int start_index, IntBuffer images, IntBuffer images_copy) {
for (int y = 0; y < height>>1; y++) {
int index_y_1 = y*width + start_index;
int index_y_2 = (height - y - 1)*width + start_index;
for (int x = 0; x < width; x++) {
int index1 = index_y_1 + x;
int index2 = index_y_2 + x;
int temp_pixel = images.get(index1 + images.position());
images_copy.put(index1, images.get(index2 + images.position()));
images_copy.put(index2, temp_pixel);
}
}
}
byte alpha = (byte) (argbColor >>> 24);
byte blue = (byte) (argbColor >>> 16);
byte green = (byte) (argbColor >>> 8);
byte red = (byte) argbColor;
/**
* Gets the native handle associated with the cursor object.
*/
Object getHandle() {
checkValid();
return cursors[index].cursorHandle;
}
int abgrColor = ((alpha & 0xff) << 24) + ((red & 0xff) << 16) + ((green & 0xff) << 8) + ((blue & 0xff));
private void checkValid() {
if (destroyed)
throw new IllegalStateException("The cursor is destroyed");
}
imageBuffer.put(i, abgrColor);
}
}
/**
* Destroy the native cursor. If the cursor is current,
* the current native cursor is set to null (the default
* OS cursor)
*/
public void destroy() {
// TODO
}
/**
* Flips the images so they're oriented according to opengl
*
* @param width Width of image
* @param height Height of images
* @param numImages How many images to flip
* @param images Source images
* @param images_copy Destination images
*/
private static void flipImages(int width, int height, int numImages, IntBuffer images, IntBuffer images_copy) {
for (int i = 0; i < numImages; i++) {
int start_index = i * width * height;
flipImage(width, height, start_index, images, images_copy);
}
}
/**
* Sets the timout property to the time it should be changed
*/
protected void setTimeout() {
checkValid();
cursors[index].timeout = System.currentTimeMillis() + cursors[index].delay;
}
/**
* @param width Width of image
* @param height Height of images
* @param start_index index into source buffer to copy to
* @param images Source images
* @param images_copy Destination images
*/
private static void flipImage(int width, int height, int start_index, IntBuffer images, IntBuffer images_copy) {
for (int y = 0; y < height >> 1; y++) {
int index_y_1 = y * width + start_index;
int index_y_2 = (height - y - 1) * width + start_index;
for (int x = 0; x < width; x++) {
int index1 = index_y_1 + x;
int index2 = index_y_2 + x;
int temp_pixel = images.get(index1 + images.position());
images_copy.put(index1, images.get(index2 + images.position()));
images_copy.put(index2, temp_pixel);
}
}
}
/**
* Determines whether this cursor has timed out
* @return true if the this cursor has timed out, false if not
*/
protected boolean hasTimedOut() {
checkValid();
return cursors.length > 1 && cursors[index].timeout < System.currentTimeMillis();
}
/**
* Gets the native handle associated with the cursor object.
*/
Object getHandle() {
checkValid();
return cursors[index].cursorHandle;
}
/**
* Changes to the next cursor
*/
protected void nextCursor() {
checkValid();
index = ++index % cursors.length;
}
private void checkValid() {
if (destroyed) throw new IllegalStateException("The cursor is destroyed");
}
/**
* A single cursor element, used when animating
*/
private static class CursorElement {
/** Handle to cursor */
final Object cursorHandle;
/**
* Destroy the native cursor. If the cursor is current,
* the current native cursor is set to null (the default
* OS cursor)
*/
public void destroy() {
// TODO
}
/** How long a delay this element should have */
final long delay;
/**
* Sets the timout property to the time it should be changed
*/
protected void setTimeout() {
checkValid();
cursors[index].timeout = System.currentTimeMillis() + cursors[index].delay;
}
/** Absolute time this element times out */
long timeout;
/**
* Determines whether this cursor has timed out
* @return true if the this cursor has timed out, false if not
*/
protected boolean hasTimedOut() {
checkValid();
return cursors.length > 1 && cursors[index].timeout < System.currentTimeMillis();
}
CursorElement(Object cursorHandle, long delay, long timeout) {
this.cursorHandle = cursorHandle;
this.delay = delay;
this.timeout = timeout;
}
}
/**
* Changes to the next cursor
*/
protected void nextCursor() {
checkValid();
index = ++index % cursors.length;
}
/**
* A single cursor element, used when animating
*/
private static class CursorElement {
/** Handle to cursor */
final Object cursorHandle;
/** How long a delay this element should have */
final long delay;
/** Absolute time this element times out */
long timeout;
CursorElement(Object cursorHandle, long delay, long timeout) {
this.cursorHandle = cursorHandle;
this.delay = delay;
this.timeout = timeout;
}
}
}
+48 -48
View File
@@ -5,53 +5,53 @@ package org.lwjglx.input;
* When the array is full the position will wrap to the beginning.
*/
class EventQueue {
private int maxEvents = 32;
private int eventCount = 0;
private int currentEventPos = -1;
private int nextEventPos = 0;
EventQueue(int maxEvents) {
this.maxEvents = maxEvents;
}
/**
* add event to the queue
*/
void add() {
eventCount++; // increment event count
if (eventCount > maxEvents) eventCount = maxEvents; // cap max events
nextEventPos++; // increment next event position
if (nextEventPos == maxEvents) nextEventPos = 0; // wrap next event position
if (nextEventPos == currentEventPos) currentEventPos++; // skip oldest event is queue full
if (currentEventPos == maxEvents) currentEventPos = 0; // wrap current event position
}
/**
* Increment the event queue
* @return - true if there is an event available
*/
boolean next() {
if (eventCount == 0) return false;
eventCount--; // decrement event count
currentEventPos++; // increment current event position
if (currentEventPos == maxEvents) currentEventPos = 0; // wrap current event position
return true;
}
int getMaxEvents() {
return maxEvents;
}
int getCurrentPos() {
return currentEventPos;
}
int getNextPos() {
return nextEventPos;
}
private int maxEvents = 32;
private int eventCount = 0;
private int currentEventPos = -1;
private int nextEventPos = 0;
EventQueue(int maxEvents) {
this.maxEvents = maxEvents;
}
/**
* add event to the queue
*/
void add() {
eventCount++; // increment event count
if (eventCount > maxEvents) eventCount = maxEvents; // cap max events
nextEventPos++; // increment next event position
if (nextEventPos == maxEvents) nextEventPos = 0; // wrap next event position
if (nextEventPos == currentEventPos) currentEventPos++; // skip oldest event is queue full
if (currentEventPos == maxEvents) currentEventPos = 0; // wrap current event position
}
/**
* Increment the event queue
* @return - true if there is an event available
*/
boolean next() {
if (eventCount == 0) return false;
eventCount--; // decrement event count
currentEventPos++; // increment current event position
if (currentEventPos == maxEvents) currentEventPos = 0; // wrap current event position
return true;
}
int getMaxEvents() {
return maxEvents;
}
int getCurrentPos() {
return currentEventPos;
}
int getNextPos() {
return nextEventPos;
}
}
+526 -305
View File
@@ -3,319 +3,540 @@ package org.lwjglx.input;
import org.lwjgl.glfw.GLFW;
public class KeyCodes {
public static int toLwjglKey(int glfwKeyCode) {
switch(glfwKeyCode) {
case GLFW.GLFW_KEY_ESCAPE : return Keyboard.KEY_ESCAPE;
case GLFW.GLFW_KEY_BACKSPACE: return Keyboard.KEY_BACK;
case GLFW.GLFW_KEY_TAB : return Keyboard.KEY_TAB;
case GLFW.GLFW_KEY_ENTER : return Keyboard.KEY_RETURN;
case GLFW.GLFW_KEY_SPACE : return Keyboard.KEY_SPACE;
case GLFW.GLFW_KEY_LEFT_CONTROL : return Keyboard.KEY_LCONTROL;
case GLFW.GLFW_KEY_LEFT_SHIFT : return Keyboard.KEY_LSHIFT;
case GLFW.GLFW_KEY_LEFT_ALT : return Keyboard.KEY_LMENU;
case GLFW.GLFW_KEY_LEFT_SUPER : return Keyboard.KEY_LMETA;
case GLFW.GLFW_KEY_RIGHT_CONTROL: return Keyboard.KEY_RCONTROL;
case GLFW.GLFW_KEY_RIGHT_SHIFT : return Keyboard.KEY_RSHIFT;
case GLFW.GLFW_KEY_RIGHT_ALT : return Keyboard.KEY_RMENU;
case GLFW.GLFW_KEY_RIGHT_SUPER : return Keyboard.KEY_RMETA;
case GLFW.GLFW_KEY_1 : return Keyboard.KEY_1;
case GLFW.GLFW_KEY_2 : return Keyboard.KEY_2;
case GLFW.GLFW_KEY_3 : return Keyboard.KEY_3;
case GLFW.GLFW_KEY_4 : return Keyboard.KEY_4;
case GLFW.GLFW_KEY_5 : return Keyboard.KEY_5;
case GLFW.GLFW_KEY_6 : return Keyboard.KEY_6;
case GLFW.GLFW_KEY_7 : return Keyboard.KEY_7;
case GLFW.GLFW_KEY_8 : return Keyboard.KEY_8;
case GLFW.GLFW_KEY_9 : return Keyboard.KEY_9;
case GLFW.GLFW_KEY_0 : return Keyboard.KEY_0;
case GLFW.GLFW_KEY_A : return Keyboard.KEY_A;
case GLFW.GLFW_KEY_B : return Keyboard.KEY_B;
case GLFW.GLFW_KEY_C : return Keyboard.KEY_C;
case GLFW.GLFW_KEY_D : return Keyboard.KEY_D;
case GLFW.GLFW_KEY_E : return Keyboard.KEY_E;
case GLFW.GLFW_KEY_F : return Keyboard.KEY_F;
case GLFW.GLFW_KEY_G : return Keyboard.KEY_G;
case GLFW.GLFW_KEY_H : return Keyboard.KEY_H;
case GLFW.GLFW_KEY_I : return Keyboard.KEY_I;
case GLFW.GLFW_KEY_J : return Keyboard.KEY_J;
case GLFW.GLFW_KEY_K : return Keyboard.KEY_K;
case GLFW.GLFW_KEY_L : return Keyboard.KEY_L;
case GLFW.GLFW_KEY_M : return Keyboard.KEY_M;
case GLFW.GLFW_KEY_N : return Keyboard.KEY_N;
case GLFW.GLFW_KEY_O : return Keyboard.KEY_O;
case GLFW.GLFW_KEY_P : return Keyboard.KEY_P;
case GLFW.GLFW_KEY_Q : return Keyboard.KEY_Q;
case GLFW.GLFW_KEY_R : return Keyboard.KEY_R;
case GLFW.GLFW_KEY_S : return Keyboard.KEY_S;
case GLFW.GLFW_KEY_T : return Keyboard.KEY_T;
case GLFW.GLFW_KEY_U : return Keyboard.KEY_U;
case GLFW.GLFW_KEY_V : return Keyboard.KEY_V;
case GLFW.GLFW_KEY_W : return Keyboard.KEY_W;
case GLFW.GLFW_KEY_X : return Keyboard.KEY_X;
case GLFW.GLFW_KEY_Y : return Keyboard.KEY_Y;
case GLFW.GLFW_KEY_Z : return Keyboard.KEY_Z;
case GLFW.GLFW_KEY_UP : return Keyboard.KEY_UP;
case GLFW.GLFW_KEY_DOWN : return Keyboard.KEY_DOWN;
case GLFW.GLFW_KEY_LEFT : return Keyboard.KEY_LEFT;
case GLFW.GLFW_KEY_RIGHT : return Keyboard.KEY_RIGHT;
case GLFW.GLFW_KEY_INSERT : return Keyboard.KEY_INSERT;
case GLFW.GLFW_KEY_DELETE : return Keyboard.KEY_DELETE;
case GLFW.GLFW_KEY_HOME : return Keyboard.KEY_HOME;
case GLFW.GLFW_KEY_END : return Keyboard.KEY_END;
case GLFW.GLFW_KEY_PAGE_UP : return Keyboard.KEY_PRIOR;
case GLFW.GLFW_KEY_PAGE_DOWN: return Keyboard.KEY_NEXT;
case GLFW.GLFW_KEY_F1 : return Keyboard.KEY_F1;
case GLFW.GLFW_KEY_F2 : return Keyboard.KEY_F2;
case GLFW.GLFW_KEY_F3 : return Keyboard.KEY_F3;
case GLFW.GLFW_KEY_F4 : return Keyboard.KEY_F4;
case GLFW.GLFW_KEY_F5 : return Keyboard.KEY_F5;
case GLFW.GLFW_KEY_F6 : return Keyboard.KEY_F6;
case GLFW.GLFW_KEY_F7 : return Keyboard.KEY_F7;
case GLFW.GLFW_KEY_F8 : return Keyboard.KEY_F8;
case GLFW.GLFW_KEY_F9 : return Keyboard.KEY_F9;
case GLFW.GLFW_KEY_F10 : return Keyboard.KEY_F10;
case GLFW.GLFW_KEY_F11 : return Keyboard.KEY_F11;
case GLFW.GLFW_KEY_F12 : return Keyboard.KEY_F12;
case GLFW.GLFW_KEY_F13 : return Keyboard.KEY_F13;
case GLFW.GLFW_KEY_F14 : return Keyboard.KEY_F14;
case GLFW.GLFW_KEY_F15 : return Keyboard.KEY_F15;
case GLFW.GLFW_KEY_F16 : return Keyboard.KEY_F16;
case GLFW.GLFW_KEY_F17 : return Keyboard.KEY_F17;
case GLFW.GLFW_KEY_F18 : return Keyboard.KEY_F18;
case GLFW.GLFW_KEY_F19 : return Keyboard.KEY_F19;
case GLFW.GLFW_KEY_KP_1 : return Keyboard.KEY_NUMPAD1;
case GLFW.GLFW_KEY_KP_2 : return Keyboard.KEY_NUMPAD2;
case GLFW.GLFW_KEY_KP_3 : return Keyboard.KEY_NUMPAD3;
case GLFW.GLFW_KEY_KP_4 : return Keyboard.KEY_NUMPAD4;
case GLFW.GLFW_KEY_KP_5 : return Keyboard.KEY_NUMPAD5;
case GLFW.GLFW_KEY_KP_6 : return Keyboard.KEY_NUMPAD6;
case GLFW.GLFW_KEY_KP_7 : return Keyboard.KEY_NUMPAD7;
case GLFW.GLFW_KEY_KP_8 : return Keyboard.KEY_NUMPAD8;
case GLFW.GLFW_KEY_KP_9 : return Keyboard.KEY_NUMPAD9;
case GLFW.GLFW_KEY_KP_0 : return Keyboard.KEY_NUMPAD0;
case GLFW.GLFW_KEY_KP_ADD : return Keyboard.KEY_ADD;
case GLFW.GLFW_KEY_KP_SUBTRACT : return Keyboard.KEY_SUBTRACT;
case GLFW.GLFW_KEY_KP_MULTIPLY : return Keyboard.KEY_MULTIPLY;
case GLFW.GLFW_KEY_KP_DIVIDE: return Keyboard.KEY_DIVIDE;
case GLFW.GLFW_KEY_KP_DECIMAL : return Keyboard.KEY_DECIMAL;
case GLFW.GLFW_KEY_KP_EQUAL : return Keyboard.KEY_NUMPADEQUALS;
case GLFW.GLFW_KEY_KP_ENTER : return Keyboard.KEY_NUMPADENTER;
case GLFW.GLFW_KEY_NUM_LOCK : return Keyboard.KEY_NUMLOCK;
case GLFW.GLFW_KEY_SEMICOLON: return Keyboard.KEY_SEMICOLON;
case GLFW.GLFW_KEY_BACKSLASH: return Keyboard.KEY_BACKSLASH;
case GLFW.GLFW_KEY_COMMA : return Keyboard.KEY_COMMA;
case GLFW.GLFW_KEY_PERIOD : return Keyboard.KEY_PERIOD;
case GLFW.GLFW_KEY_SLASH : return Keyboard.KEY_SLASH;
case GLFW.GLFW_KEY_GRAVE_ACCENT : return Keyboard.KEY_GRAVE;
case GLFW.GLFW_KEY_CAPS_LOCK: return Keyboard.KEY_CAPITAL;
case GLFW.GLFW_KEY_SCROLL_LOCK : return Keyboard.KEY_SCROLL;
case GLFW.GLFW_KEY_WORLD_1 : return Keyboard.KEY_CIRCUMFLEX; // TODO not sure if correct
case GLFW.GLFW_KEY_PAUSE : return Keyboard.KEY_PAUSE;
case GLFW.GLFW_KEY_MINUS : return Keyboard.KEY_MINUS;
case GLFW.GLFW_KEY_EQUAL : return Keyboard.KEY_EQUALS;
case GLFW.GLFW_KEY_LEFT_BRACKET : return Keyboard.KEY_LBRACKET;
case GLFW.GLFW_KEY_RIGHT_BRACKET: return Keyboard.KEY_RBRACKET;
case GLFW.GLFW_KEY_APOSTROPHE : return Keyboard.KEY_APOSTROPHE;
// public static final int KEY_AT = 0x91; /* (NEC PC98) */
// public static final int KEY_COLON = 0x92; /* (NEC PC98) */
// public static final int KEY_UNDERLINE = 0x93; /* (NEC PC98) */
public static int toLwjglKey(int glfwKeyCode) {
// public static final int KEY_KANA = 0x70; /* (Japanese keyboard) */
// public static final int KEY_CONVERT = 0x79; /* (Japanese keyboard) */
// public static final int KEY_NOCONVERT = 0x7B; /* (Japanese keyboard) */
// public static final int KEY_YEN = 0x7D; /* (Japanese keyboard) */
// public static final int KEY_CIRCUMFLEX = 0x90; /* (Japanese keyboard) */
// public static final int KEY_KANJI = 0x94; /* (Japanese keyboard) */
// public static final int KEY_STOP = 0x95; /* (NEC PC98) */
// public static final int KEY_AX = 0x96; /* (Japan AX) */
// public static final int KEY_UNLABELED = 0x97; /* (J3100) */
// public static final int KEY_SECTION = 0xA7; /* Section symbol (Mac) */
// public static final int KEY_NUMPADCOMMA = 0xB3; /* , on numeric keypad (NEC PC98) */
// public static final int KEY_SYSRQ = 0xB7;
// public static final int KEY_FUNCTION = 0xC4; /* Function (Mac) */
// public static final int KEY_CLEAR = 0xDA; /* Clear key (Mac) */
switch (glfwKeyCode) {
case GLFW.GLFW_KEY_ESCAPE:
return Keyboard.KEY_ESCAPE;
case GLFW.GLFW_KEY_BACKSPACE:
return Keyboard.KEY_BACK;
case GLFW.GLFW_KEY_TAB:
return Keyboard.KEY_TAB;
case GLFW.GLFW_KEY_ENTER:
return Keyboard.KEY_RETURN;
case GLFW.GLFW_KEY_SPACE:
return Keyboard.KEY_SPACE;
// public static final int KEY_APPS = 0xDD; /* AppMenu key */
// public static final int KEY_POWER = 0xDE;
// public static final int KEY_SLEEP = 0xDF;
case GLFW.GLFW_KEY_LEFT_CONTROL:
return Keyboard.KEY_LCONTROL;
case GLFW.GLFW_KEY_LEFT_SHIFT:
return Keyboard.KEY_LSHIFT;
case GLFW.GLFW_KEY_LEFT_ALT:
return Keyboard.KEY_LMENU;
case GLFW.GLFW_KEY_LEFT_SUPER:
return Keyboard.KEY_LMETA;
default: System.out.println("UNKNOWN GLFW KEY CODE: " + glfwKeyCode);
return Keyboard.KEY_NONE;
}
}
public static int toGlfwKey(int lwjglKeyCode) {
switch(lwjglKeyCode) {
case Keyboard.KEY_ESCAPE : return GLFW.GLFW_KEY_ESCAPE;
case Keyboard.KEY_BACK : return GLFW.GLFW_KEY_BACKSPACE;
case Keyboard.KEY_TAB : return GLFW.GLFW_KEY_TAB;
case Keyboard.KEY_RETURN : return GLFW.GLFW_KEY_ENTER;
case Keyboard.KEY_SPACE : return GLFW.GLFW_KEY_SPACE;
case Keyboard.KEY_LCONTROL : return GLFW.GLFW_KEY_LEFT_CONTROL;
case Keyboard.KEY_LSHIFT : return GLFW.GLFW_KEY_LEFT_SHIFT;
case Keyboard.KEY_LMENU : return GLFW.GLFW_KEY_LEFT_ALT;
case Keyboard.KEY_LMETA : return GLFW.GLFW_KEY_LEFT_SUPER;
case Keyboard.KEY_RCONTROL : return GLFW.GLFW_KEY_RIGHT_CONTROL;
case Keyboard.KEY_RSHIFT : return GLFW.GLFW_KEY_RIGHT_SHIFT;
case Keyboard.KEY_RMENU : return GLFW.GLFW_KEY_RIGHT_ALT;
case Keyboard.KEY_RMETA : return GLFW.GLFW_KEY_RIGHT_SUPER;
case Keyboard.KEY_1 : return GLFW.GLFW_KEY_1;
case Keyboard.KEY_2 : return GLFW.GLFW_KEY_2;
case Keyboard.KEY_3 : return GLFW.GLFW_KEY_3;
case Keyboard.KEY_4 : return GLFW.GLFW_KEY_4;
case Keyboard.KEY_5 : return GLFW.GLFW_KEY_5;
case Keyboard.KEY_6 : return GLFW.GLFW_KEY_6;
case Keyboard.KEY_7 : return GLFW.GLFW_KEY_7;
case Keyboard.KEY_8 : return GLFW.GLFW_KEY_8;
case Keyboard.KEY_9 : return GLFW.GLFW_KEY_9;
case Keyboard.KEY_0 : return GLFW.GLFW_KEY_0;
case Keyboard.KEY_A : return GLFW.GLFW_KEY_A;
case Keyboard.KEY_B : return GLFW.GLFW_KEY_B;
case Keyboard.KEY_C : return GLFW.GLFW_KEY_C;
case Keyboard.KEY_D : return GLFW.GLFW_KEY_D;
case Keyboard.KEY_E : return GLFW.GLFW_KEY_E;
case Keyboard.KEY_F : return GLFW.GLFW_KEY_F;
case Keyboard.KEY_G : return GLFW.GLFW_KEY_G;
case Keyboard.KEY_H : return GLFW.GLFW_KEY_H;
case Keyboard.KEY_I : return GLFW.GLFW_KEY_I;
case Keyboard.KEY_J : return GLFW.GLFW_KEY_J;
case Keyboard.KEY_K : return GLFW.GLFW_KEY_K;
case Keyboard.KEY_L : return GLFW.GLFW_KEY_L;
case Keyboard.KEY_M : return GLFW.GLFW_KEY_M;
case Keyboard.KEY_N : return GLFW.GLFW_KEY_N;
case Keyboard.KEY_O : return GLFW.GLFW_KEY_O;
case Keyboard.KEY_P : return GLFW.GLFW_KEY_P;
case Keyboard.KEY_Q : return GLFW.GLFW_KEY_Q;
case Keyboard.KEY_R : return GLFW.GLFW_KEY_R;
case Keyboard.KEY_S : return GLFW.GLFW_KEY_S;
case Keyboard.KEY_T : return GLFW.GLFW_KEY_T;
case Keyboard.KEY_U : return GLFW.GLFW_KEY_U;
case Keyboard.KEY_V : return GLFW.GLFW_KEY_V;
case Keyboard.KEY_W : return GLFW.GLFW_KEY_W;
case Keyboard.KEY_X : return GLFW.GLFW_KEY_X;
case Keyboard.KEY_Y : return GLFW.GLFW_KEY_Y;
case Keyboard.KEY_Z : return GLFW.GLFW_KEY_Z;
case Keyboard.KEY_UP : return GLFW.GLFW_KEY_UP;
case Keyboard.KEY_DOWN : return GLFW.GLFW_KEY_DOWN;
case Keyboard.KEY_LEFT : return GLFW.GLFW_KEY_LEFT;
case Keyboard.KEY_RIGHT : return GLFW.GLFW_KEY_RIGHT;
case Keyboard.KEY_INSERT : return GLFW.GLFW_KEY_INSERT;
case Keyboard.KEY_DELETE : return GLFW.GLFW_KEY_DELETE;
case Keyboard.KEY_HOME : return GLFW.GLFW_KEY_HOME;
case Keyboard.KEY_END : return GLFW.GLFW_KEY_END;
case Keyboard.KEY_PRIOR : return GLFW.GLFW_KEY_PAGE_UP;
case Keyboard.KEY_NEXT : return GLFW.GLFW_KEY_PAGE_DOWN;
case Keyboard.KEY_F1 : return GLFW.GLFW_KEY_F1;
case Keyboard.KEY_F2 : return GLFW.GLFW_KEY_F2;
case Keyboard.KEY_F3 : return GLFW.GLFW_KEY_F3;
case Keyboard.KEY_F4 : return GLFW.GLFW_KEY_F4;
case Keyboard.KEY_F5 : return GLFW.GLFW_KEY_F5;
case Keyboard.KEY_F6 : return GLFW.GLFW_KEY_F6;
case Keyboard.KEY_F7 : return GLFW.GLFW_KEY_F7;
case Keyboard.KEY_F8 : return GLFW.GLFW_KEY_F8;
case Keyboard.KEY_F9 : return GLFW.GLFW_KEY_F9;
case Keyboard.KEY_F10 : return GLFW.GLFW_KEY_F10;
case Keyboard.KEY_F11 : return GLFW.GLFW_KEY_F11;
case Keyboard.KEY_F12 : return GLFW.GLFW_KEY_F12;
case Keyboard.KEY_F13 : return GLFW.GLFW_KEY_F13;
case Keyboard.KEY_F14 : return GLFW.GLFW_KEY_F14;
case Keyboard.KEY_F15 : return GLFW.GLFW_KEY_F15;
case Keyboard.KEY_F16 : return GLFW.GLFW_KEY_F16;
case Keyboard.KEY_F17 : return GLFW.GLFW_KEY_F17;
case Keyboard.KEY_F18 : return GLFW.GLFW_KEY_F18;
case Keyboard.KEY_F19 : return GLFW.GLFW_KEY_F19;
case Keyboard.KEY_NUMPAD1 : return GLFW.GLFW_KEY_KP_1;
case Keyboard.KEY_NUMPAD2 : return GLFW.GLFW_KEY_KP_2;
case Keyboard.KEY_NUMPAD3 : return GLFW.GLFW_KEY_KP_3;
case Keyboard.KEY_NUMPAD4 : return GLFW.GLFW_KEY_KP_4;
case Keyboard.KEY_NUMPAD5 : return GLFW.GLFW_KEY_KP_5;
case Keyboard.KEY_NUMPAD6 : return GLFW.GLFW_KEY_KP_6;
case Keyboard.KEY_NUMPAD7 : return GLFW.GLFW_KEY_KP_7;
case Keyboard.KEY_NUMPAD8 : return GLFW.GLFW_KEY_KP_8;
case Keyboard.KEY_NUMPAD9 : return GLFW.GLFW_KEY_KP_9;
case Keyboard.KEY_NUMPAD0 : return GLFW.GLFW_KEY_KP_0;
case Keyboard.KEY_ADD : return GLFW.GLFW_KEY_KP_ADD;
case Keyboard.KEY_SUBTRACT : return GLFW.GLFW_KEY_KP_SUBTRACT;
case Keyboard.KEY_MULTIPLY : return GLFW.GLFW_KEY_KP_MULTIPLY;
case Keyboard.KEY_DIVIDE : return GLFW.GLFW_KEY_KP_DIVIDE;
case Keyboard.KEY_DECIMAL : return GLFW.GLFW_KEY_KP_DECIMAL;
case Keyboard.KEY_NUMPADEQUALS : return GLFW.GLFW_KEY_KP_EQUAL;
case Keyboard.KEY_NUMPADENTER : return GLFW.GLFW_KEY_KP_ENTER;
case Keyboard.KEY_NUMLOCK : return GLFW.GLFW_KEY_NUM_LOCK;
case Keyboard.KEY_SEMICOLON : return GLFW.GLFW_KEY_SEMICOLON;
case Keyboard.KEY_BACKSLASH : return GLFW.GLFW_KEY_BACKSLASH;
case Keyboard.KEY_COMMA : return GLFW.GLFW_KEY_COMMA;
case Keyboard.KEY_PERIOD : return GLFW.GLFW_KEY_PERIOD;
case Keyboard.KEY_SLASH : return GLFW.GLFW_KEY_SLASH;
case Keyboard.KEY_GRAVE : return GLFW.GLFW_KEY_GRAVE_ACCENT;
case GLFW.GLFW_KEY_RIGHT_CONTROL:
return Keyboard.KEY_RCONTROL;
case GLFW.GLFW_KEY_RIGHT_SHIFT:
return Keyboard.KEY_RSHIFT;
case GLFW.GLFW_KEY_RIGHT_ALT:
return Keyboard.KEY_RMENU;
case GLFW.GLFW_KEY_RIGHT_SUPER:
return Keyboard.KEY_RMETA;
case Keyboard.KEY_CAPITAL : return GLFW.GLFW_KEY_CAPS_LOCK;
case Keyboard.KEY_SCROLL : return GLFW.GLFW_KEY_SCROLL_LOCK;
case Keyboard.KEY_PAUSE : return GLFW.GLFW_KEY_PAUSE;
case Keyboard.KEY_CIRCUMFLEX: return GLFW.GLFW_KEY_WORLD_1; // TODO not sure if correct
case GLFW.GLFW_KEY_1:
return Keyboard.KEY_1;
case GLFW.GLFW_KEY_2:
return Keyboard.KEY_2;
case GLFW.GLFW_KEY_3:
return Keyboard.KEY_3;
case GLFW.GLFW_KEY_4:
return Keyboard.KEY_4;
case GLFW.GLFW_KEY_5:
return Keyboard.KEY_5;
case GLFW.GLFW_KEY_6:
return Keyboard.KEY_6;
case GLFW.GLFW_KEY_7:
return Keyboard.KEY_7;
case GLFW.GLFW_KEY_8:
return Keyboard.KEY_8;
case GLFW.GLFW_KEY_9:
return Keyboard.KEY_9;
case GLFW.GLFW_KEY_0:
return Keyboard.KEY_0;
case Keyboard.KEY_MINUS : return GLFW.GLFW_KEY_MINUS;
case Keyboard.KEY_EQUALS : return GLFW.GLFW_KEY_EQUAL;
case Keyboard.KEY_LBRACKET : return GLFW.GLFW_KEY_LEFT_BRACKET;
case Keyboard.KEY_RBRACKET : return GLFW.GLFW_KEY_RIGHT_BRACKET;
case Keyboard.KEY_APOSTROPHE: return GLFW.GLFW_KEY_APOSTROPHE;
// public static final int KEY_AT = 0x91; /* (NEC PC98) */
// public static final int KEY_COLON = 0x92; /* (NEC PC98) */
// public static final int KEY_UNDERLINE = 0x93; /* (NEC PC98) */
case GLFW.GLFW_KEY_A:
return Keyboard.KEY_A;
case GLFW.GLFW_KEY_B:
return Keyboard.KEY_B;
case GLFW.GLFW_KEY_C:
return Keyboard.KEY_C;
case GLFW.GLFW_KEY_D:
return Keyboard.KEY_D;
case GLFW.GLFW_KEY_E:
return Keyboard.KEY_E;
case GLFW.GLFW_KEY_F:
return Keyboard.KEY_F;
case GLFW.GLFW_KEY_G:
return Keyboard.KEY_G;
case GLFW.GLFW_KEY_H:
return Keyboard.KEY_H;
case GLFW.GLFW_KEY_I:
return Keyboard.KEY_I;
case GLFW.GLFW_KEY_J:
return Keyboard.KEY_J;
case GLFW.GLFW_KEY_K:
return Keyboard.KEY_K;
case GLFW.GLFW_KEY_L:
return Keyboard.KEY_L;
case GLFW.GLFW_KEY_M:
return Keyboard.KEY_M;
case GLFW.GLFW_KEY_N:
return Keyboard.KEY_N;
case GLFW.GLFW_KEY_O:
return Keyboard.KEY_O;
case GLFW.GLFW_KEY_P:
return Keyboard.KEY_P;
case GLFW.GLFW_KEY_Q:
return Keyboard.KEY_Q;
case GLFW.GLFW_KEY_R:
return Keyboard.KEY_R;
case GLFW.GLFW_KEY_S:
return Keyboard.KEY_S;
case GLFW.GLFW_KEY_T:
return Keyboard.KEY_T;
case GLFW.GLFW_KEY_U:
return Keyboard.KEY_U;
case GLFW.GLFW_KEY_V:
return Keyboard.KEY_V;
case GLFW.GLFW_KEY_W:
return Keyboard.KEY_W;
case GLFW.GLFW_KEY_X:
return Keyboard.KEY_X;
case GLFW.GLFW_KEY_Y:
return Keyboard.KEY_Y;
case GLFW.GLFW_KEY_Z:
return Keyboard.KEY_Z;
// public static final int KEY_KANA = 0x70; /* (Japanese keyboard) */
// public static final int KEY_CONVERT = 0x79; /* (Japanese keyboard) */
// public static final int KEY_NOCONVERT = 0x7B; /* (Japanese keyboard) */
// public static final int KEY_YEN = 0x7D; /* (Japanese keyboard) */
// public static final int KEY_CIRCUMFLEX = 0x90; /* (Japanese keyboard) */
// public static final int KEY_KANJI = 0x94; /* (Japanese keyboard) */
// public static final int KEY_STOP = 0x95; /* (NEC PC98) */
// public static final int KEY_AX = 0x96; /* (Japan AX) */
// public static final int KEY_UNLABELED = 0x97; /* (J3100) */
// public static final int KEY_SECTION = 0xA7; /* Section symbol (Mac) */
// public static final int KEY_NUMPADCOMMA = 0xB3; /* , on numeric keypad (NEC PC98) */
// public static final int KEY_SYSRQ = 0xB7;
// public static final int KEY_FUNCTION = 0xC4; /* Function (Mac) */
// public static final int KEY_CLEAR = 0xDA; /* Clear key (Mac) */
case GLFW.GLFW_KEY_UP:
return Keyboard.KEY_UP;
case GLFW.GLFW_KEY_DOWN:
return Keyboard.KEY_DOWN;
case GLFW.GLFW_KEY_LEFT:
return Keyboard.KEY_LEFT;
case GLFW.GLFW_KEY_RIGHT:
return Keyboard.KEY_RIGHT;
// public static final int KEY_APPS = 0xDD; /* AppMenu key */
// public static final int KEY_POWER = 0xDE;
// public static final int KEY_SLEEP = 0xDF;
case GLFW.GLFW_KEY_INSERT:
return Keyboard.KEY_INSERT;
case GLFW.GLFW_KEY_DELETE:
return Keyboard.KEY_DELETE;
case GLFW.GLFW_KEY_HOME:
return Keyboard.KEY_HOME;
case GLFW.GLFW_KEY_END:
return Keyboard.KEY_END;
case GLFW.GLFW_KEY_PAGE_UP:
return Keyboard.KEY_PRIOR;
case GLFW.GLFW_KEY_PAGE_DOWN:
return Keyboard.KEY_NEXT;
default: System.out.println("UNKNOWN LWJGL KEY CODE: " + lwjglKeyCode);
return GLFW.GLFW_KEY_UNKNOWN;
}
}
case GLFW.GLFW_KEY_F1:
return Keyboard.KEY_F1;
case GLFW.GLFW_KEY_F2:
return Keyboard.KEY_F2;
case GLFW.GLFW_KEY_F3:
return Keyboard.KEY_F3;
case GLFW.GLFW_KEY_F4:
return Keyboard.KEY_F4;
case GLFW.GLFW_KEY_F5:
return Keyboard.KEY_F5;
case GLFW.GLFW_KEY_F6:
return Keyboard.KEY_F6;
case GLFW.GLFW_KEY_F7:
return Keyboard.KEY_F7;
case GLFW.GLFW_KEY_F8:
return Keyboard.KEY_F8;
case GLFW.GLFW_KEY_F9:
return Keyboard.KEY_F9;
case GLFW.GLFW_KEY_F10:
return Keyboard.KEY_F10;
case GLFW.GLFW_KEY_F11:
return Keyboard.KEY_F11;
case GLFW.GLFW_KEY_F12:
return Keyboard.KEY_F12;
case GLFW.GLFW_KEY_F13:
return Keyboard.KEY_F13;
case GLFW.GLFW_KEY_F14:
return Keyboard.KEY_F14;
case GLFW.GLFW_KEY_F15:
return Keyboard.KEY_F15;
case GLFW.GLFW_KEY_F16:
return Keyboard.KEY_F16;
case GLFW.GLFW_KEY_F17:
return Keyboard.KEY_F17;
case GLFW.GLFW_KEY_F18:
return Keyboard.KEY_F18;
case GLFW.GLFW_KEY_F19:
return Keyboard.KEY_F19;
case GLFW.GLFW_KEY_KP_1:
return Keyboard.KEY_NUMPAD1;
case GLFW.GLFW_KEY_KP_2:
return Keyboard.KEY_NUMPAD2;
case GLFW.GLFW_KEY_KP_3:
return Keyboard.KEY_NUMPAD3;
case GLFW.GLFW_KEY_KP_4:
return Keyboard.KEY_NUMPAD4;
case GLFW.GLFW_KEY_KP_5:
return Keyboard.KEY_NUMPAD5;
case GLFW.GLFW_KEY_KP_6:
return Keyboard.KEY_NUMPAD6;
case GLFW.GLFW_KEY_KP_7:
return Keyboard.KEY_NUMPAD7;
case GLFW.GLFW_KEY_KP_8:
return Keyboard.KEY_NUMPAD8;
case GLFW.GLFW_KEY_KP_9:
return Keyboard.KEY_NUMPAD9;
case GLFW.GLFW_KEY_KP_0:
return Keyboard.KEY_NUMPAD0;
case GLFW.GLFW_KEY_KP_ADD:
return Keyboard.KEY_ADD;
case GLFW.GLFW_KEY_KP_SUBTRACT:
return Keyboard.KEY_SUBTRACT;
case GLFW.GLFW_KEY_KP_MULTIPLY:
return Keyboard.KEY_MULTIPLY;
case GLFW.GLFW_KEY_KP_DIVIDE:
return Keyboard.KEY_DIVIDE;
case GLFW.GLFW_KEY_KP_DECIMAL:
return Keyboard.KEY_DECIMAL;
case GLFW.GLFW_KEY_KP_EQUAL:
return Keyboard.KEY_NUMPADEQUALS;
case GLFW.GLFW_KEY_KP_ENTER:
return Keyboard.KEY_NUMPADENTER;
case GLFW.GLFW_KEY_NUM_LOCK:
return Keyboard.KEY_NUMLOCK;
case GLFW.GLFW_KEY_SEMICOLON:
return Keyboard.KEY_SEMICOLON;
case GLFW.GLFW_KEY_BACKSLASH:
return Keyboard.KEY_BACKSLASH;
case GLFW.GLFW_KEY_COMMA:
return Keyboard.KEY_COMMA;
case GLFW.GLFW_KEY_PERIOD:
return Keyboard.KEY_PERIOD;
case GLFW.GLFW_KEY_SLASH:
return Keyboard.KEY_SLASH;
case GLFW.GLFW_KEY_GRAVE_ACCENT:
return Keyboard.KEY_GRAVE;
case GLFW.GLFW_KEY_CAPS_LOCK:
return Keyboard.KEY_CAPITAL;
case GLFW.GLFW_KEY_SCROLL_LOCK:
return Keyboard.KEY_SCROLL;
case GLFW.GLFW_KEY_WORLD_1:
return Keyboard.KEY_CIRCUMFLEX; // TODO not sure if correct
case GLFW.GLFW_KEY_PAUSE:
return Keyboard.KEY_PAUSE;
case GLFW.GLFW_KEY_MINUS:
return Keyboard.KEY_MINUS;
case GLFW.GLFW_KEY_EQUAL:
return Keyboard.KEY_EQUALS;
case GLFW.GLFW_KEY_LEFT_BRACKET:
return Keyboard.KEY_LBRACKET;
case GLFW.GLFW_KEY_RIGHT_BRACKET:
return Keyboard.KEY_RBRACKET;
case GLFW.GLFW_KEY_APOSTROPHE:
return Keyboard.KEY_APOSTROPHE;
// public static final int KEY_AT = 0x91; /* (NEC PC98) */
// public static final int KEY_COLON = 0x92; /* (NEC PC98) */
// public static final int KEY_UNDERLINE = 0x93; /* (NEC PC98) */
// public static final int KEY_KANA = 0x70; /* (Japanese keyboard) */
// public static final int KEY_CONVERT = 0x79; /* (Japanese keyboard) */
// public static final int KEY_NOCONVERT = 0x7B; /* (Japanese keyboard) */
// public static final int KEY_YEN = 0x7D; /* (Japanese keyboard) */
// public static final int KEY_CIRCUMFLEX = 0x90; /* (Japanese keyboard) */
// public static final int KEY_KANJI = 0x94; /* (Japanese keyboard) */
// public static final int KEY_STOP = 0x95; /* (NEC PC98) */
// public static final int KEY_AX = 0x96; /* (Japan AX) */
// public static final int KEY_UNLABELED = 0x97; /* (J3100) */
// public static final int KEY_SECTION = 0xA7; /* Section symbol (Mac) */
// public static final int KEY_NUMPADCOMMA = 0xB3; /* , on numeric keypad (NEC PC98) */
// public static final int KEY_SYSRQ = 0xB7;
// public static final int KEY_FUNCTION = 0xC4; /* Function (Mac) */
// public static final int KEY_CLEAR = 0xDA; /* Clear key (Mac) */
// public static final int KEY_APPS = 0xDD; /* AppMenu key */
// public static final int KEY_POWER = 0xDE;
// public static final int KEY_SLEEP = 0xDF;
default:
System.out.println("UNKNOWN GLFW KEY CODE: " + glfwKeyCode);
return Keyboard.KEY_NONE;
}
}
public static int toGlfwKey(int lwjglKeyCode) {
switch (lwjglKeyCode) {
case Keyboard.KEY_ESCAPE:
return GLFW.GLFW_KEY_ESCAPE;
case Keyboard.KEY_BACK:
return GLFW.GLFW_KEY_BACKSPACE;
case Keyboard.KEY_TAB:
return GLFW.GLFW_KEY_TAB;
case Keyboard.KEY_RETURN:
return GLFW.GLFW_KEY_ENTER;
case Keyboard.KEY_SPACE:
return GLFW.GLFW_KEY_SPACE;
case Keyboard.KEY_LCONTROL:
return GLFW.GLFW_KEY_LEFT_CONTROL;
case Keyboard.KEY_LSHIFT:
return GLFW.GLFW_KEY_LEFT_SHIFT;
case Keyboard.KEY_LMENU:
return GLFW.GLFW_KEY_LEFT_ALT;
case Keyboard.KEY_LMETA:
return GLFW.GLFW_KEY_LEFT_SUPER;
case Keyboard.KEY_RCONTROL:
return GLFW.GLFW_KEY_RIGHT_CONTROL;
case Keyboard.KEY_RSHIFT:
return GLFW.GLFW_KEY_RIGHT_SHIFT;
case Keyboard.KEY_RMENU:
return GLFW.GLFW_KEY_RIGHT_ALT;
case Keyboard.KEY_RMETA:
return GLFW.GLFW_KEY_RIGHT_SUPER;
case Keyboard.KEY_1:
return GLFW.GLFW_KEY_1;
case Keyboard.KEY_2:
return GLFW.GLFW_KEY_2;
case Keyboard.KEY_3:
return GLFW.GLFW_KEY_3;
case Keyboard.KEY_4:
return GLFW.GLFW_KEY_4;
case Keyboard.KEY_5:
return GLFW.GLFW_KEY_5;
case Keyboard.KEY_6:
return GLFW.GLFW_KEY_6;
case Keyboard.KEY_7:
return GLFW.GLFW_KEY_7;
case Keyboard.KEY_8:
return GLFW.GLFW_KEY_8;
case Keyboard.KEY_9:
return GLFW.GLFW_KEY_9;
case Keyboard.KEY_0:
return GLFW.GLFW_KEY_0;
case Keyboard.KEY_A:
return GLFW.GLFW_KEY_A;
case Keyboard.KEY_B:
return GLFW.GLFW_KEY_B;
case Keyboard.KEY_C:
return GLFW.GLFW_KEY_C;
case Keyboard.KEY_D:
return GLFW.GLFW_KEY_D;
case Keyboard.KEY_E:
return GLFW.GLFW_KEY_E;
case Keyboard.KEY_F:
return GLFW.GLFW_KEY_F;
case Keyboard.KEY_G:
return GLFW.GLFW_KEY_G;
case Keyboard.KEY_H:
return GLFW.GLFW_KEY_H;
case Keyboard.KEY_I:
return GLFW.GLFW_KEY_I;
case Keyboard.KEY_J:
return GLFW.GLFW_KEY_J;
case Keyboard.KEY_K:
return GLFW.GLFW_KEY_K;
case Keyboard.KEY_L:
return GLFW.GLFW_KEY_L;
case Keyboard.KEY_M:
return GLFW.GLFW_KEY_M;
case Keyboard.KEY_N:
return GLFW.GLFW_KEY_N;
case Keyboard.KEY_O:
return GLFW.GLFW_KEY_O;
case Keyboard.KEY_P:
return GLFW.GLFW_KEY_P;
case Keyboard.KEY_Q:
return GLFW.GLFW_KEY_Q;
case Keyboard.KEY_R:
return GLFW.GLFW_KEY_R;
case Keyboard.KEY_S:
return GLFW.GLFW_KEY_S;
case Keyboard.KEY_T:
return GLFW.GLFW_KEY_T;
case Keyboard.KEY_U:
return GLFW.GLFW_KEY_U;
case Keyboard.KEY_V:
return GLFW.GLFW_KEY_V;
case Keyboard.KEY_W:
return GLFW.GLFW_KEY_W;
case Keyboard.KEY_X:
return GLFW.GLFW_KEY_X;
case Keyboard.KEY_Y:
return GLFW.GLFW_KEY_Y;
case Keyboard.KEY_Z:
return GLFW.GLFW_KEY_Z;
case Keyboard.KEY_UP:
return GLFW.GLFW_KEY_UP;
case Keyboard.KEY_DOWN:
return GLFW.GLFW_KEY_DOWN;
case Keyboard.KEY_LEFT:
return GLFW.GLFW_KEY_LEFT;
case Keyboard.KEY_RIGHT:
return GLFW.GLFW_KEY_RIGHT;
case Keyboard.KEY_INSERT:
return GLFW.GLFW_KEY_INSERT;
case Keyboard.KEY_DELETE:
return GLFW.GLFW_KEY_DELETE;
case Keyboard.KEY_HOME:
return GLFW.GLFW_KEY_HOME;
case Keyboard.KEY_END:
return GLFW.GLFW_KEY_END;
case Keyboard.KEY_PRIOR:
return GLFW.GLFW_KEY_PAGE_UP;
case Keyboard.KEY_NEXT:
return GLFW.GLFW_KEY_PAGE_DOWN;
case Keyboard.KEY_F1:
return GLFW.GLFW_KEY_F1;
case Keyboard.KEY_F2:
return GLFW.GLFW_KEY_F2;
case Keyboard.KEY_F3:
return GLFW.GLFW_KEY_F3;
case Keyboard.KEY_F4:
return GLFW.GLFW_KEY_F4;
case Keyboard.KEY_F5:
return GLFW.GLFW_KEY_F5;
case Keyboard.KEY_F6:
return GLFW.GLFW_KEY_F6;
case Keyboard.KEY_F7:
return GLFW.GLFW_KEY_F7;
case Keyboard.KEY_F8:
return GLFW.GLFW_KEY_F8;
case Keyboard.KEY_F9:
return GLFW.GLFW_KEY_F9;
case Keyboard.KEY_F10:
return GLFW.GLFW_KEY_F10;
case Keyboard.KEY_F11:
return GLFW.GLFW_KEY_F11;
case Keyboard.KEY_F12:
return GLFW.GLFW_KEY_F12;
case Keyboard.KEY_F13:
return GLFW.GLFW_KEY_F13;
case Keyboard.KEY_F14:
return GLFW.GLFW_KEY_F14;
case Keyboard.KEY_F15:
return GLFW.GLFW_KEY_F15;
case Keyboard.KEY_F16:
return GLFW.GLFW_KEY_F16;
case Keyboard.KEY_F17:
return GLFW.GLFW_KEY_F17;
case Keyboard.KEY_F18:
return GLFW.GLFW_KEY_F18;
case Keyboard.KEY_F19:
return GLFW.GLFW_KEY_F19;
case Keyboard.KEY_NUMPAD1:
return GLFW.GLFW_KEY_KP_1;
case Keyboard.KEY_NUMPAD2:
return GLFW.GLFW_KEY_KP_2;
case Keyboard.KEY_NUMPAD3:
return GLFW.GLFW_KEY_KP_3;
case Keyboard.KEY_NUMPAD4:
return GLFW.GLFW_KEY_KP_4;
case Keyboard.KEY_NUMPAD5:
return GLFW.GLFW_KEY_KP_5;
case Keyboard.KEY_NUMPAD6:
return GLFW.GLFW_KEY_KP_6;
case Keyboard.KEY_NUMPAD7:
return GLFW.GLFW_KEY_KP_7;
case Keyboard.KEY_NUMPAD8:
return GLFW.GLFW_KEY_KP_8;
case Keyboard.KEY_NUMPAD9:
return GLFW.GLFW_KEY_KP_9;
case Keyboard.KEY_NUMPAD0:
return GLFW.GLFW_KEY_KP_0;
case Keyboard.KEY_ADD:
return GLFW.GLFW_KEY_KP_ADD;
case Keyboard.KEY_SUBTRACT:
return GLFW.GLFW_KEY_KP_SUBTRACT;
case Keyboard.KEY_MULTIPLY:
return GLFW.GLFW_KEY_KP_MULTIPLY;
case Keyboard.KEY_DIVIDE:
return GLFW.GLFW_KEY_KP_DIVIDE;
case Keyboard.KEY_DECIMAL:
return GLFW.GLFW_KEY_KP_DECIMAL;
case Keyboard.KEY_NUMPADEQUALS:
return GLFW.GLFW_KEY_KP_EQUAL;
case Keyboard.KEY_NUMPADENTER:
return GLFW.GLFW_KEY_KP_ENTER;
case Keyboard.KEY_NUMLOCK:
return GLFW.GLFW_KEY_NUM_LOCK;
case Keyboard.KEY_SEMICOLON:
return GLFW.GLFW_KEY_SEMICOLON;
case Keyboard.KEY_BACKSLASH:
return GLFW.GLFW_KEY_BACKSLASH;
case Keyboard.KEY_COMMA:
return GLFW.GLFW_KEY_COMMA;
case Keyboard.KEY_PERIOD:
return GLFW.GLFW_KEY_PERIOD;
case Keyboard.KEY_SLASH:
return GLFW.GLFW_KEY_SLASH;
case Keyboard.KEY_GRAVE:
return GLFW.GLFW_KEY_GRAVE_ACCENT;
case Keyboard.KEY_CAPITAL:
return GLFW.GLFW_KEY_CAPS_LOCK;
case Keyboard.KEY_SCROLL:
return GLFW.GLFW_KEY_SCROLL_LOCK;
case Keyboard.KEY_PAUSE:
return GLFW.GLFW_KEY_PAUSE;
case Keyboard.KEY_CIRCUMFLEX:
return GLFW.GLFW_KEY_WORLD_1; // TODO not sure if correct
case Keyboard.KEY_MINUS:
return GLFW.GLFW_KEY_MINUS;
case Keyboard.KEY_EQUALS:
return GLFW.GLFW_KEY_EQUAL;
case Keyboard.KEY_LBRACKET:
return GLFW.GLFW_KEY_LEFT_BRACKET;
case Keyboard.KEY_RBRACKET:
return GLFW.GLFW_KEY_RIGHT_BRACKET;
case Keyboard.KEY_APOSTROPHE:
return GLFW.GLFW_KEY_APOSTROPHE;
// public static final int KEY_AT = 0x91; /* (NEC PC98) */
// public static final int KEY_COLON = 0x92; /* (NEC PC98) */
// public static final int KEY_UNDERLINE = 0x93; /* (NEC PC98) */
// public static final int KEY_KANA = 0x70; /* (Japanese keyboard) */
// public static final int KEY_CONVERT = 0x79; /* (Japanese keyboard) */
// public static final int KEY_NOCONVERT = 0x7B; /* (Japanese keyboard) */
// public static final int KEY_YEN = 0x7D; /* (Japanese keyboard) */
// public static final int KEY_CIRCUMFLEX = 0x90; /* (Japanese keyboard) */
// public static final int KEY_KANJI = 0x94; /* (Japanese keyboard) */
// public static final int KEY_STOP = 0x95; /* (NEC PC98) */
// public static final int KEY_AX = 0x96; /* (Japan AX) */
// public static final int KEY_UNLABELED = 0x97; /* (J3100) */
// public static final int KEY_SECTION = 0xA7; /* Section symbol (Mac) */
// public static final int KEY_NUMPADCOMMA = 0xB3; /* , on numeric keypad (NEC PC98) */
// public static final int KEY_SYSRQ = 0xB7;
// public static final int KEY_FUNCTION = 0xC4; /* Function (Mac) */
// public static final int KEY_CLEAR = 0xDA; /* Clear key (Mac) */
// public static final int KEY_APPS = 0xDD; /* AppMenu key */
// public static final int KEY_POWER = 0xDE;
// public static final int KEY_SLEEP = 0xDF;
default:
System.out.println("UNKNOWN LWJGL KEY CODE: " + lwjglKeyCode);
return GLFW.GLFW_KEY_UNKNOWN;
}
}
}
+264 -273
View File
@@ -4,289 +4,280 @@ import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.HashMap;
import java.util.Map;
import org.lwjgl.glfw.GLFW;
import org.lwjglx.LWJGLException;
import org.lwjglx.Sys;
import org.lwjglx.opengl.Display;
public class Keyboard {
/**
* The special character meaning that no
* character was translated for the event.
*/
public static final int CHAR_NONE = '\0';
/**
* The special keycode meaning that only the
* translated character is valid.
*/
public static final int KEY_NONE = 0x00;
/**
* The special character meaning that no
* character was translated for the event.
*/
public static final int CHAR_NONE = '\0';
public static final int KEY_ESCAPE = 0x01;
public static final int KEY_1 = 0x02;
public static final int KEY_2 = 0x03;
public static final int KEY_3 = 0x04;
public static final int KEY_4 = 0x05;
public static final int KEY_5 = 0x06;
public static final int KEY_6 = 0x07;
public static final int KEY_7 = 0x08;
public static final int KEY_8 = 0x09;
public static final int KEY_9 = 0x0A;
public static final int KEY_0 = 0x0B;
public static final int KEY_MINUS = 0x0C; /* - on main keyboard */
public static final int KEY_EQUALS = 0x0D;
public static final int KEY_BACK = 0x0E; /* backspace */
public static final int KEY_TAB = 0x0F;
public static final int KEY_Q = 0x10;
public static final int KEY_W = 0x11;
public static final int KEY_E = 0x12;
public static final int KEY_R = 0x13;
public static final int KEY_T = 0x14;
public static final int KEY_Y = 0x15;
public static final int KEY_U = 0x16;
public static final int KEY_I = 0x17;
public static final int KEY_O = 0x18;
public static final int KEY_P = 0x19;
public static final int KEY_LBRACKET = 0x1A;
public static final int KEY_RBRACKET = 0x1B;
public static final int KEY_RETURN = 0x1C; /* Enter on main keyboard */
public static final int KEY_LCONTROL = 0x1D;
public static final int KEY_A = 0x1E;
public static final int KEY_S = 0x1F;
public static final int KEY_D = 0x20;
public static final int KEY_F = 0x21;
public static final int KEY_G = 0x22;
public static final int KEY_H = 0x23;
public static final int KEY_J = 0x24;
public static final int KEY_K = 0x25;
public static final int KEY_L = 0x26;
public static final int KEY_SEMICOLON = 0x27;
public static final int KEY_APOSTROPHE = 0x28;
public static final int KEY_GRAVE = 0x29; /* accent grave */
public static final int KEY_LSHIFT = 0x2A;
public static final int KEY_BACKSLASH = 0x2B;
public static final int KEY_Z = 0x2C;
public static final int KEY_X = 0x2D;
public static final int KEY_C = 0x2E;
public static final int KEY_V = 0x2F;
public static final int KEY_B = 0x30;
public static final int KEY_N = 0x31;
public static final int KEY_M = 0x32;
public static final int KEY_COMMA = 0x33;
public static final int KEY_PERIOD = 0x34; /* . on main keyboard */
public static final int KEY_SLASH = 0x35; /* / on main keyboard */
public static final int KEY_RSHIFT = 0x36;
public static final int KEY_MULTIPLY = 0x37; /* * on numeric keypad */
public static final int KEY_LMENU = 0x38; /* left Alt */
public static final int KEY_SPACE = 0x39;
public static final int KEY_CAPITAL = 0x3A;
public static final int KEY_F1 = 0x3B;
public static final int KEY_F2 = 0x3C;
public static final int KEY_F3 = 0x3D;
public static final int KEY_F4 = 0x3E;
public static final int KEY_F5 = 0x3F;
public static final int KEY_F6 = 0x40;
public static final int KEY_F7 = 0x41;
public static final int KEY_F8 = 0x42;
public static final int KEY_F9 = 0x43;
public static final int KEY_F10 = 0x44;
public static final int KEY_NUMLOCK = 0x45;
public static final int KEY_SCROLL = 0x46; /* Scroll Lock */
public static final int KEY_NUMPAD7 = 0x47;
public static final int KEY_NUMPAD8 = 0x48;
public static final int KEY_NUMPAD9 = 0x49;
public static final int KEY_SUBTRACT = 0x4A; /* - on numeric keypad */
public static final int KEY_NUMPAD4 = 0x4B;
public static final int KEY_NUMPAD5 = 0x4C;
public static final int KEY_NUMPAD6 = 0x4D;
public static final int KEY_ADD = 0x4E; /* + on numeric keypad */
public static final int KEY_NUMPAD1 = 0x4F;
public static final int KEY_NUMPAD2 = 0x50;
public static final int KEY_NUMPAD3 = 0x51;
public static final int KEY_NUMPAD0 = 0x52;
public static final int KEY_DECIMAL = 0x53; /* . on numeric keypad */
public static final int KEY_F11 = 0x57;
public static final int KEY_F12 = 0x58;
public static final int KEY_F13 = 0x64; /* (NEC PC98) */
public static final int KEY_F14 = 0x65; /* (NEC PC98) */
public static final int KEY_F15 = 0x66; /* (NEC PC98) */
public static final int KEY_F16 = 0x67; /* Extended Function keys - (Mac) */
public static final int KEY_F17 = 0x68;
public static final int KEY_F18 = 0x69;
public static final int KEY_KANA = 0x70; /* (Japanese keyboard) */
public static final int KEY_F19 = 0x71; /* Extended Function keys - (Mac) */
public static final int KEY_CONVERT = 0x79; /* (Japanese keyboard) */
public static final int KEY_NOCONVERT = 0x7B; /* (Japanese keyboard) */
public static final int KEY_YEN = 0x7D; /* (Japanese keyboard) */
public static final int KEY_NUMPADEQUALS = 0x8D; /* = on numeric keypad (NEC PC98) */
public static final int KEY_CIRCUMFLEX = 0x90; /* (Japanese keyboard) */
public static final int KEY_AT = 0x91; /* (NEC PC98) */
public static final int KEY_COLON = 0x92; /* (NEC PC98) */
public static final int KEY_UNDERLINE = 0x93; /* (NEC PC98) */
public static final int KEY_KANJI = 0x94; /* (Japanese keyboard) */
public static final int KEY_STOP = 0x95; /* (NEC PC98) */
public static final int KEY_AX = 0x96; /* (Japan AX) */
public static final int KEY_UNLABELED = 0x97; /* (J3100) */
public static final int KEY_NUMPADENTER = 0x9C; /* Enter on numeric keypad */
public static final int KEY_RCONTROL = 0x9D;
public static final int KEY_SECTION = 0xA7; /* Section symbol (Mac) */
public static final int KEY_NUMPADCOMMA = 0xB3; /* , on numeric keypad (NEC PC98) */
public static final int KEY_DIVIDE = 0xB5; /* / on numeric keypad */
public static final int KEY_SYSRQ = 0xB7;
public static final int KEY_RMENU = 0xB8; /* right Alt */
public static final int KEY_FUNCTION = 0xC4; /* Function (Mac) */
public static final int KEY_PAUSE = 0xC5; /* Pause */
public static final int KEY_HOME = 0xC7; /* Home on arrow keypad */
public static final int KEY_UP = 0xC8; /* UpArrow on arrow keypad */
public static final int KEY_PRIOR = 0xC9; /* PgUp on arrow keypad */
public static final int KEY_LEFT = 0xCB; /* LeftArrow on arrow keypad */
public static final int KEY_RIGHT = 0xCD; /* RightArrow on arrow keypad */
public static final int KEY_END = 0xCF; /* End on arrow keypad */
public static final int KEY_DOWN = 0xD0; /* DownArrow on arrow keypad */
public static final int KEY_NEXT = 0xD1; /* PgDn on arrow keypad */
public static final int KEY_INSERT = 0xD2; /* Insert on arrow keypad */
public static final int KEY_DELETE = 0xD3; /* Delete on arrow keypad */
public static final int KEY_CLEAR = 0xDA; /* Clear key (Mac) */
public static final int KEY_LMETA = 0xDB; /* Left Windows/Option key */
public static final int KEY_LWIN = KEY_LMETA; /* Left Windows key */
public static final int KEY_RMETA = 0xDC; /* Right Windows/Option key */
public static final int KEY_RWIN = KEY_RMETA; /* Right Windows key */
public static final int KEY_APPS = 0xDD; /* AppMenu key */
public static final int KEY_POWER = 0xDE;
public static final int KEY_SLEEP = 0xDF;
/**
* The special keycode meaning that only the
* translated character is valid.
*/
public static final int KEY_NONE = 0x00;
private static EventQueue queue = new EventQueue(32);
//private static int maxEvents = 32;
//private static int eventCount = 0;
//private static int currentEventPos = -1;
//private static int nextEventPos = 0;
private static int[] keyEvents = new int[queue.getMaxEvents()];
private static boolean[] keyEventStates = new boolean[queue.getMaxEvents()];
private static long[] nanoTimeEvents = new long[queue.getMaxEvents()];
private static char[] keyEventChars = new char[256];
public static final int KEYBOARD_SIZE = 256;
private static final String[] keyName = new String[KEYBOARD_SIZE];
private static final Map<String, Integer> keyMap = new HashMap<String, Integer>(253);
static {
// Use reflection to find out key names
Field[] fields = Keyboard.class.getFields();
try {
for ( Field field : fields ) {
if ( Modifier.isStatic(field.getModifiers())
&& Modifier.isPublic(field.getModifiers())
&& Modifier.isFinal(field.getModifiers())
&& field.getType().equals(int.class)
&& field.getName().startsWith("KEY_")
&& !field.getName().endsWith("WIN") ) { /* Don't use deprecated names */
public static final int KEY_ESCAPE = 0x01;
public static final int KEY_1 = 0x02;
public static final int KEY_2 = 0x03;
public static final int KEY_3 = 0x04;
public static final int KEY_4 = 0x05;
public static final int KEY_5 = 0x06;
public static final int KEY_6 = 0x07;
public static final int KEY_7 = 0x08;
public static final int KEY_8 = 0x09;
public static final int KEY_9 = 0x0A;
public static final int KEY_0 = 0x0B;
public static final int KEY_MINUS = 0x0C; /* - on main keyboard */
public static final int KEY_EQUALS = 0x0D;
public static final int KEY_BACK = 0x0E; /* backspace */
public static final int KEY_TAB = 0x0F;
public static final int KEY_Q = 0x10;
public static final int KEY_W = 0x11;
public static final int KEY_E = 0x12;
public static final int KEY_R = 0x13;
public static final int KEY_T = 0x14;
public static final int KEY_Y = 0x15;
public static final int KEY_U = 0x16;
public static final int KEY_I = 0x17;
public static final int KEY_O = 0x18;
public static final int KEY_P = 0x19;
public static final int KEY_LBRACKET = 0x1A;
public static final int KEY_RBRACKET = 0x1B;
public static final int KEY_RETURN = 0x1C; /* Enter on main keyboard */
public static final int KEY_LCONTROL = 0x1D;
public static final int KEY_A = 0x1E;
public static final int KEY_S = 0x1F;
public static final int KEY_D = 0x20;
public static final int KEY_F = 0x21;
public static final int KEY_G = 0x22;
public static final int KEY_H = 0x23;
public static final int KEY_J = 0x24;
public static final int KEY_K = 0x25;
public static final int KEY_L = 0x26;
public static final int KEY_SEMICOLON = 0x27;
public static final int KEY_APOSTROPHE = 0x28;
public static final int KEY_GRAVE = 0x29; /* accent grave */
public static final int KEY_LSHIFT = 0x2A;
public static final int KEY_BACKSLASH = 0x2B;
public static final int KEY_Z = 0x2C;
public static final int KEY_X = 0x2D;
public static final int KEY_C = 0x2E;
public static final int KEY_V = 0x2F;
public static final int KEY_B = 0x30;
public static final int KEY_N = 0x31;
public static final int KEY_M = 0x32;
public static final int KEY_COMMA = 0x33;
public static final int KEY_PERIOD = 0x34; /* . on main keyboard */
public static final int KEY_SLASH = 0x35; /* / on main keyboard */
public static final int KEY_RSHIFT = 0x36;
public static final int KEY_MULTIPLY = 0x37; /* * on numeric keypad */
public static final int KEY_LMENU = 0x38; /* left Alt */
public static final int KEY_SPACE = 0x39;
public static final int KEY_CAPITAL = 0x3A;
public static final int KEY_F1 = 0x3B;
public static final int KEY_F2 = 0x3C;
public static final int KEY_F3 = 0x3D;
public static final int KEY_F4 = 0x3E;
public static final int KEY_F5 = 0x3F;
public static final int KEY_F6 = 0x40;
public static final int KEY_F7 = 0x41;
public static final int KEY_F8 = 0x42;
public static final int KEY_F9 = 0x43;
public static final int KEY_F10 = 0x44;
public static final int KEY_NUMLOCK = 0x45;
public static final int KEY_SCROLL = 0x46; /* Scroll Lock */
public static final int KEY_NUMPAD7 = 0x47;
public static final int KEY_NUMPAD8 = 0x48;
public static final int KEY_NUMPAD9 = 0x49;
public static final int KEY_SUBTRACT = 0x4A; /* - on numeric keypad */
public static final int KEY_NUMPAD4 = 0x4B;
public static final int KEY_NUMPAD5 = 0x4C;
public static final int KEY_NUMPAD6 = 0x4D;
public static final int KEY_ADD = 0x4E; /* + on numeric keypad */
public static final int KEY_NUMPAD1 = 0x4F;
public static final int KEY_NUMPAD2 = 0x50;
public static final int KEY_NUMPAD3 = 0x51;
public static final int KEY_NUMPAD0 = 0x52;
public static final int KEY_DECIMAL = 0x53; /* . on numeric keypad */
public static final int KEY_F11 = 0x57;
public static final int KEY_F12 = 0x58;
public static final int KEY_F13 = 0x64; /* (NEC PC98) */
public static final int KEY_F14 = 0x65; /* (NEC PC98) */
public static final int KEY_F15 = 0x66; /* (NEC PC98) */
public static final int KEY_F16 = 0x67; /* Extended Function keys - (Mac) */
public static final int KEY_F17 = 0x68;
public static final int KEY_F18 = 0x69;
public static final int KEY_KANA = 0x70; /* (Japanese keyboard) */
public static final int KEY_F19 = 0x71; /* Extended Function keys - (Mac) */
public static final int KEY_CONVERT = 0x79; /* (Japanese keyboard) */
public static final int KEY_NOCONVERT = 0x7B; /* (Japanese keyboard) */
public static final int KEY_YEN = 0x7D; /* (Japanese keyboard) */
public static final int KEY_NUMPADEQUALS = 0x8D; /* = on numeric keypad (NEC PC98) */
public static final int KEY_CIRCUMFLEX = 0x90; /* (Japanese keyboard) */
public static final int KEY_AT = 0x91; /* (NEC PC98) */
public static final int KEY_COLON = 0x92; /* (NEC PC98) */
public static final int KEY_UNDERLINE = 0x93; /* (NEC PC98) */
public static final int KEY_KANJI = 0x94; /* (Japanese keyboard) */
public static final int KEY_STOP = 0x95; /* (NEC PC98) */
public static final int KEY_AX = 0x96; /* (Japan AX) */
public static final int KEY_UNLABELED = 0x97; /* (J3100) */
public static final int KEY_NUMPADENTER = 0x9C; /* Enter on numeric keypad */
public static final int KEY_RCONTROL = 0x9D;
public static final int KEY_SECTION = 0xA7; /* Section symbol (Mac) */
public static final int KEY_NUMPADCOMMA = 0xB3; /* , on numeric keypad (NEC PC98) */
public static final int KEY_DIVIDE = 0xB5; /* / on numeric keypad */
public static final int KEY_SYSRQ = 0xB7;
public static final int KEY_RMENU = 0xB8; /* right Alt */
public static final int KEY_FUNCTION = 0xC4; /* Function (Mac) */
public static final int KEY_PAUSE = 0xC5; /* Pause */
public static final int KEY_HOME = 0xC7; /* Home on arrow keypad */
public static final int KEY_UP = 0xC8; /* UpArrow on arrow keypad */
public static final int KEY_PRIOR = 0xC9; /* PgUp on arrow keypad */
public static final int KEY_LEFT = 0xCB; /* LeftArrow on arrow keypad */
public static final int KEY_RIGHT = 0xCD; /* RightArrow on arrow keypad */
public static final int KEY_END = 0xCF; /* End on arrow keypad */
public static final int KEY_DOWN = 0xD0; /* DownArrow on arrow keypad */
public static final int KEY_NEXT = 0xD1; /* PgDn on arrow keypad */
public static final int KEY_INSERT = 0xD2; /* Insert on arrow keypad */
public static final int KEY_DELETE = 0xD3; /* Delete on arrow keypad */
public static final int KEY_CLEAR = 0xDA; /* Clear key (Mac) */
public static final int KEY_LMETA = 0xDB; /* Left Windows/Option key */
public static final int KEY_LWIN = KEY_LMETA; /* Left Windows key */
public static final int KEY_RMETA = 0xDC; /* Right Windows/Option key */
public static final int KEY_RWIN = KEY_RMETA; /* Right Windows key */
public static final int KEY_APPS = 0xDD; /* AppMenu key */
public static final int KEY_POWER = 0xDE;
public static final int KEY_SLEEP = 0xDF;
int key = field.getInt(null);
String name = field.getName().substring(4);
keyName[key] = name;
keyMap.put(name, key);
}
private static EventQueue queue = new EventQueue(32);
// private static int maxEvents = 32;
}
} catch (Exception e) {
}
// private static int eventCount = 0;
// private static int currentEventPos = -1;
// private static int nextEventPos = 0;
}
public static void addKeyEvent(int key, boolean pressed) {
//eventCount++;
//if (eventCount > maxEvents) eventCount = maxEvents;
keyEvents[queue.getNextPos()] = KeyCodes.toLwjglKey(key);
keyEventStates[queue.getNextPos()] = pressed;
nanoTimeEvents[queue.getNextPos()] = Sys.getNanoTime();
queue.add();
/*nextEventPos++;
if (nextEventPos == maxEvents) nextEventPos = 0;
if (currentEventPos == nextEventPos) currentEventPos++;
if (currentEventPos == maxEvents) currentEventPos = 0;*/
}
public static void addCharEvent(int key, char c) {
int index = KeyCodes.toLwjglKey(key);
keyEventChars[index] = c;
}
public static void create() throws LWJGLException {
}
public static boolean isKeyDown(int key) {
return GLFW.glfwGetKey(Display.getWindow(), KeyCodes.toGlfwKey(key)) == GLFW.GLFW_PRESS;
}
public static void poll() {
// TODO
}
public static void enableRepeatEvents(boolean enable) {
// TODO
System.out.println("TODO: Implement Keyboad.enableRepeatEvents(boolean)");
}
public static boolean isRepeatEvent() {
// TODO
return false;
}
public static boolean next() {
return queue.next();
/*if (eventCount == 0) return false;
eventCount--;
currentEventPos++;
if (currentEventPos == maxEvents) currentEventPos = 0;
return true;*/
}
public static int getEventKey() {
return keyEvents[queue.getCurrentPos()];
}
public static char getEventCharacter() {
return keyEventChars[getEventKey()];
}
public static boolean getEventKeyState() {
return keyEventStates[queue.getCurrentPos()];
}
public static long getEventNanoseconds() {
return nanoTimeEvents[queue.getCurrentPos()];
}
public static String getKeyName(int key) {
return keyName[key];
}
public static int getKeyIndex(java.lang.String keyName) {
Integer ret = keyMap.get(keyName);
if (ret == null)
return KEY_NONE;
else
return ret;
}
public static boolean isCreated() {
return Display.isCreated();
}
public static void destroy() {
}
private static int[] keyEvents = new int[queue.getMaxEvents()];
private static boolean[] keyEventStates = new boolean[queue.getMaxEvents()];
private static long[] nanoTimeEvents = new long[queue.getMaxEvents()];
private static char[] keyEventChars = new char[256];
public static final int KEYBOARD_SIZE = 256;
private static final String[] keyName = new String[KEYBOARD_SIZE];
private static final Map<String, Integer> keyMap = new HashMap<String, Integer>(253);
static {
// Use reflection to find out key names
Field[] fields = Keyboard.class.getFields();
try {
for (Field field : fields) {
if (Modifier.isStatic(field.getModifiers())
&& Modifier.isPublic(field.getModifiers())
&& Modifier.isFinal(field.getModifiers())
&& field.getType().equals(int.class)
&& field.getName().startsWith("KEY_")
&& !field.getName().endsWith("WIN")) {
/* Don't use deprecated names */
int key = field.getInt(null);
String name = field.getName().substring(4);
keyName[key] = name;
keyMap.put(name, key);
}
}
} catch (Exception e) {
}
}
public static void addKeyEvent(int key, boolean pressed) {
// eventCount++;
// if (eventCount > maxEvents) eventCount = maxEvents;
keyEvents[queue.getNextPos()] = KeyCodes.toLwjglKey(key);
keyEventStates[queue.getNextPos()] = pressed;
nanoTimeEvents[queue.getNextPos()] = Sys.getNanoTime();
queue.add();
/*nextEventPos++;
if (nextEventPos == maxEvents) nextEventPos = 0;
if (currentEventPos == nextEventPos) currentEventPos++;
if (currentEventPos == maxEvents) currentEventPos = 0;*/
}
public static void addCharEvent(int key, char c) {
int index = KeyCodes.toLwjglKey(key);
keyEventChars[index] = c;
}
public static void create() throws LWJGLException {}
public static boolean isKeyDown(int key) {
return GLFW.glfwGetKey(Display.getWindow(), KeyCodes.toGlfwKey(key)) == GLFW.GLFW_PRESS;
}
public static void poll() {
// TODO
}
public static void enableRepeatEvents(boolean enable) {
// TODO
System.out.println("TODO: Implement Keyboad.enableRepeatEvents(boolean)");
}
public static boolean isRepeatEvent() {
// TODO
return false;
}
public static boolean next() {
return queue.next();
/*if (eventCount == 0) return false;
eventCount--;
currentEventPos++;
if (currentEventPos == maxEvents) currentEventPos = 0;
return true;*/
}
public static int getEventKey() {
return keyEvents[queue.getCurrentPos()];
}
public static char getEventCharacter() {
return keyEventChars[getEventKey()];
}
public static boolean getEventKeyState() {
return keyEventStates[queue.getCurrentPos()];
}
public static long getEventNanoseconds() {
return nanoTimeEvents[queue.getCurrentPos()];
}
public static String getKeyName(int key) {
return keyName[key];
}
public static int getKeyIndex(java.lang.String keyName) {
Integer ret = keyMap.get(keyName);
if (ret == null) return KEY_NONE;
else return ret;
}
public static boolean isCreated() {
return Display.isCreated();
}
public static void destroy() {}
}
+167 -173
View File
@@ -6,178 +6,172 @@ import org.lwjglx.Sys;
import org.lwjglx.opengl.Display;
public class Mouse {
private static boolean grabbed = false;
private static int lastX = 0;
private static int lastY = 0;
private static int latestX = 0;
private static int latestY = 0;
private static int x = 0;
private static int y = 0;
private static EventQueue queue = new EventQueue(32);
private static int[] buttonEvents = new int[queue.getMaxEvents()];
private static boolean[] buttonEventStates = new boolean[queue.getMaxEvents()];
private static int[] xEvents = new int[queue.getMaxEvents()];
private static int[] yEvents = new int[queue.getMaxEvents()];
private static int[] lastxEvents = new int[queue.getMaxEvents()];
private static int[] lastyEvents = new int[queue.getMaxEvents()];
private static long[] nanoTimeEvents = new long[queue.getMaxEvents()];
private static boolean clipPostionToDisplay = true;
public static void addMoveEvent(double mouseX, double mouseY) {
latestX = (int)mouseX;
latestY = Display.getHeight() - (int)mouseY;
lastxEvents[queue.getNextPos()] = xEvents[queue.getNextPos()];
lastyEvents[queue.getNextPos()] = yEvents[queue.getNextPos()];
xEvents[queue.getNextPos()] = latestX;
yEvents[queue.getNextPos()] = latestY;
buttonEvents[queue.getNextPos()] = -1;
buttonEventStates[queue.getNextPos()] = false;
nanoTimeEvents[queue.getNextPos()] = Sys.getNanoTime();
queue.add();
}
public static void addButtonEvent(int button, boolean pressed) {
lastxEvents[queue.getNextPos()] = xEvents[queue.getNextPos()];
lastyEvents[queue.getNextPos()] = yEvents[queue.getNextPos()];
xEvents[queue.getNextPos()] = latestX;
yEvents[queue.getNextPos()] = latestY;
buttonEvents[queue.getNextPos()] = button;
buttonEventStates[queue.getNextPos()] = pressed;
nanoTimeEvents[queue.getNextPos()] = Sys.getNanoTime();
queue.add();
}
public static void poll() {
lastX = x;
lastY = y;
if (!grabbed && clipPostionToDisplay) {
if (latestX < 0) latestX = 0;
if (latestY < 0) latestY = 0;
if (latestX > Display.getWidth()-1) latestX = Display.getWidth() - 1;
if (latestY > Display.getHeight()-1) latestY = Display.getHeight() - 1;
}
x = latestX;
y = latestY;
}
public static void create() throws LWJGLException {
}
public static boolean isCreated() {
return Display.isCreated();
}
public static void setGrabbed(boolean grab) {
GLFW.glfwSetInputMode(Display.getWindow(),
GLFW.GLFW_CURSOR,
grab ? GLFW.GLFW_CURSOR_DISABLED : GLFW.GLFW_CURSOR_NORMAL);
grabbed = grab;
}
public static boolean isGrabbed() {
return grabbed;
}
public static boolean isButtonDown(int button) {
return GLFW.glfwGetMouseButton(Display.getWindow(), button) == GLFW.GLFW_PRESS;
}
public static boolean next() {
return queue.next();
}
public static int getEventX() {
return xEvents[queue.getCurrentPos()];
}
public static int getEventY() {
return yEvents[queue.getCurrentPos()];
}
public static int getEventDX() {
return xEvents[queue.getCurrentPos()] - lastxEvents[queue.getCurrentPos()];
}
public static int getEventDY() {
return yEvents[queue.getCurrentPos()] - lastyEvents[queue.getCurrentPos()];
}
public static long getEventNanoseconds() {
return nanoTimeEvents[queue.getCurrentPos()];
}
public static int getEventButton() {
return buttonEvents[queue.getCurrentPos()];
}
public static boolean getEventButtonState() {
return buttonEventStates[queue.getCurrentPos()];
}
public static int getEventDWheel() {
return 0; // TODO
}
public static int getX() {
return x;
}
public static int getY() {
return y;
}
public static int getDX() {
return x - lastX;
}
public static int getDY() {
return y - lastY;
}
public static int getDWheel() {
// TODO
return 0;
}
public static int getButtonCount() {
return 8; // max mouse buttons supported by GLFW
}
public static void setClipMouseCoordinatesToWindow(boolean clip) {
clipPostionToDisplay = clip;
}
public static void setCursorPosition(int new_x, int new_y) {
GLFW.glfwSetCursorPos(Display.getWindow(), new_x, new_y);
}
public static Cursor setNativeCursor(Cursor cursor) throws LWJGLException {
// TODO
System.out.println("TODO: Implement Mouse.setNativeCursor(Cursor)");
return null;
}
public static void destroy() {
}
private static boolean grabbed = false;
private static int lastX = 0;
private static int lastY = 0;
private static int latestX = 0;
private static int latestY = 0;
private static int x = 0;
private static int y = 0;
private static EventQueue queue = new EventQueue(32);
private static int[] buttonEvents = new int[queue.getMaxEvents()];
private static boolean[] buttonEventStates = new boolean[queue.getMaxEvents()];
private static int[] xEvents = new int[queue.getMaxEvents()];
private static int[] yEvents = new int[queue.getMaxEvents()];
private static int[] lastxEvents = new int[queue.getMaxEvents()];
private static int[] lastyEvents = new int[queue.getMaxEvents()];
private static long[] nanoTimeEvents = new long[queue.getMaxEvents()];
private static boolean clipPostionToDisplay = true;
public static void addMoveEvent(double mouseX, double mouseY) {
latestX = (int) mouseX;
latestY = Display.getHeight() - (int) mouseY;
lastxEvents[queue.getNextPos()] = xEvents[queue.getNextPos()];
lastyEvents[queue.getNextPos()] = yEvents[queue.getNextPos()];
xEvents[queue.getNextPos()] = latestX;
yEvents[queue.getNextPos()] = latestY;
buttonEvents[queue.getNextPos()] = -1;
buttonEventStates[queue.getNextPos()] = false;
nanoTimeEvents[queue.getNextPos()] = Sys.getNanoTime();
queue.add();
}
public static void addButtonEvent(int button, boolean pressed) {
lastxEvents[queue.getNextPos()] = xEvents[queue.getNextPos()];
lastyEvents[queue.getNextPos()] = yEvents[queue.getNextPos()];
xEvents[queue.getNextPos()] = latestX;
yEvents[queue.getNextPos()] = latestY;
buttonEvents[queue.getNextPos()] = button;
buttonEventStates[queue.getNextPos()] = pressed;
nanoTimeEvents[queue.getNextPos()] = Sys.getNanoTime();
queue.add();
}
public static void poll() {
lastX = x;
lastY = y;
if (!grabbed && clipPostionToDisplay) {
if (latestX < 0) latestX = 0;
if (latestY < 0) latestY = 0;
if (latestX > Display.getWidth() - 1) latestX = Display.getWidth() - 1;
if (latestY > Display.getHeight() - 1) latestY = Display.getHeight() - 1;
}
x = latestX;
y = latestY;
}
public static void create() throws LWJGLException {}
public static boolean isCreated() {
return Display.isCreated();
}
public static void setGrabbed(boolean grab) {
GLFW.glfwSetInputMode(
Display.getWindow(), GLFW.GLFW_CURSOR, grab ? GLFW.GLFW_CURSOR_DISABLED : GLFW.GLFW_CURSOR_NORMAL);
grabbed = grab;
}
public static boolean isGrabbed() {
return grabbed;
}
public static boolean isButtonDown(int button) {
return GLFW.glfwGetMouseButton(Display.getWindow(), button) == GLFW.GLFW_PRESS;
}
public static boolean next() {
return queue.next();
}
public static int getEventX() {
return xEvents[queue.getCurrentPos()];
}
public static int getEventY() {
return yEvents[queue.getCurrentPos()];
}
public static int getEventDX() {
return xEvents[queue.getCurrentPos()] - lastxEvents[queue.getCurrentPos()];
}
public static int getEventDY() {
return yEvents[queue.getCurrentPos()] - lastyEvents[queue.getCurrentPos()];
}
public static long getEventNanoseconds() {
return nanoTimeEvents[queue.getCurrentPos()];
}
public static int getEventButton() {
return buttonEvents[queue.getCurrentPos()];
}
public static boolean getEventButtonState() {
return buttonEventStates[queue.getCurrentPos()];
}
public static int getEventDWheel() {
return 0; // TODO
}
public static int getX() {
return x;
}
public static int getY() {
return y;
}
public static int getDX() {
return x - lastX;
}
public static int getDY() {
return y - lastY;
}
public static int getDWheel() {
// TODO
return 0;
}
public static int getButtonCount() {
return 8; // max mouse buttons supported by GLFW
}
public static void setClipMouseCoordinatesToWindow(boolean clip) {
clipPostionToDisplay = clip;
}
public static void setCursorPosition(int new_x, int new_y) {
GLFW.glfwSetCursorPos(Display.getWindow(), new_x, new_y);
}
public static Cursor setNativeCursor(Cursor cursor) throws LWJGLException {
// TODO
System.out.println("TODO: Implement Mouse.setNativeCursor(Cursor)");
return null;
}
public static void destroy() {}
}
+47 -49
View File
@@ -1,7 +1,6 @@
package org.lwjglx.openal;
import java.nio.IntBuffer;
import org.lwjgl.BufferUtils;
import org.lwjgl.openal.ALContext;
import org.lwjgl.openal.ALDevice;
@@ -9,57 +8,56 @@ import org.lwjglx.LWJGLException;
import org.lwjglx.Sys;
public class AL {
static ALContext alContext;
static ALCdevice alcDevice;
private static boolean created = false;
static {
Sys.initialize(); // init using dummy sys method
}
public static void create() throws LWJGLException {
if (alContext == null) {
ALDevice alDevice = ALDevice.create();
IntBuffer attribs = BufferUtils.createIntBuffer(16);
attribs.put(org.lwjgl.openal.ALC10.ALC_FREQUENCY);
attribs.put(44100);
static ALContext alContext;
static ALCdevice alcDevice;
attribs.put(org.lwjgl.openal.ALC10.ALC_REFRESH);
attribs.put(60);
private static boolean created = false;
attribs.put(org.lwjgl.openal.ALC10.ALC_SYNC);
attribs.put(org.lwjgl.openal.ALC10.ALC_FALSE);
static {
Sys.initialize(); // init using dummy sys method
}
attribs.put(0);
attribs.flip();
long contextHandle = org.lwjgl.openal.ALC10.alcCreateContext(alDevice.getPointer(), attribs);
alContext = new ALContext(alDevice, contextHandle);
alcDevice = new ALCdevice(contextHandle);
created = true;
}
}
public static boolean isCreated() {
return created;
}
public static void destroy() {
org.lwjgl.openal.AL.destroy(alContext);
alContext = null;
alcDevice = null;
created = false;
}
public static ALCdevice getDevice() {
return alcDevice;
}
public static void create() throws LWJGLException {
if (alContext == null) {
ALDevice alDevice = ALDevice.create();
IntBuffer attribs = BufferUtils.createIntBuffer(16);
attribs.put(org.lwjgl.openal.ALC10.ALC_FREQUENCY);
attribs.put(44100);
attribs.put(org.lwjgl.openal.ALC10.ALC_REFRESH);
attribs.put(60);
attribs.put(org.lwjgl.openal.ALC10.ALC_SYNC);
attribs.put(org.lwjgl.openal.ALC10.ALC_FALSE);
attribs.put(0);
attribs.flip();
long contextHandle = org.lwjgl.openal.ALC10.alcCreateContext(alDevice.getPointer(), attribs);
alContext = new ALContext(alDevice, contextHandle);
alcDevice = new ALCdevice(contextHandle);
created = true;
}
}
public static boolean isCreated() {
return created;
}
public static void destroy() {
org.lwjgl.openal.AL.destroy(alContext);
alContext = null;
alcDevice = null;
created = false;
}
public static ALCdevice getDevice() {
return alcDevice;
}
}
+69 -70
View File
@@ -1,75 +1,74 @@
package org.lwjglx.openal;
public class AL10 {
public static final int AL_NO_ERROR = org.lwjgl.openal.AL10.AL_NO_ERROR;
public static final int AL_BUFFER = org.lwjgl.openal.AL10.AL_BUFFER;
public static final int AL_SOURCE_STATE = org.lwjgl.openal.AL10.AL_SOURCE_STATE;
public static final int AL_PLAYING = org.lwjgl.openal.AL10.AL_PLAYING;
public static final int AL_LOOPING = org.lwjgl.openal.AL10.AL_LOOPING;
public static final int AL_TRUE = org.lwjgl.openal.AL10.AL_TRUE;
public static final int AL_REFERENCE_DISTANCE = org.lwjgl.openal.AL10.AL_REFERENCE_DISTANCE;
public static final int AL_ROLLOFF_FACTOR = org.lwjgl.openal.AL10.AL_ROLLOFF_FACTOR;
public static final int AL_POSITION = org.lwjgl.openal.AL10.AL_POSITION;
public static void alGenBuffers(java.nio.IntBuffer buffers) {
org.lwjgl.openal.AL10.alGenBuffers(buffers);
}
public static void alGenSources(java.nio.IntBuffer sources) {
org.lwjgl.openal.AL10.alGenSources(sources);
}
public static void alBufferData(int buffer, int format, java.nio.ByteBuffer data, int freq) {
org.lwjgl.openal.AL10.alBufferData(buffer, format, data, freq);
}
public static void alSourcei(int source, int pname, int value) {
org.lwjgl.openal.AL10.alSourcei(source, pname, value);
}
public static int alGetSourcei(int source, int pname) {
return org.lwjgl.openal.AL10.alGetSourcei(source, pname);
}
public static String alGetString(int pname) {
return org.lwjgl.openal.AL10.alGetString(pname);
}
public static int alGetError() {
return org.lwjgl.openal.AL10.alGetError();
}
public static void alSourcef(int source, int pname, float value) {
org.lwjgl.openal.AL10.alSourcef(source, pname, value);
}
public static void alSourcePlay(int source) {
org.lwjgl.openal.AL10.alSourcePlay(source);
}
public static void alSourceStop(java.nio.IntBuffer sources) {
org.lwjgl.openal.AL10.alSourceStop(sources);
}
public static void alDeleteSources(java.nio.IntBuffer sources) {
org.lwjgl.openal.AL10.alDeleteSources(sources);
}
public static void alDeleteBuffers(java.nio.IntBuffer buffers) {
org.lwjgl.openal.AL10.alDeleteBuffers(buffers);
}
public static void alListener3f(int pname, float v1, float v2, float v3) {
org.lwjgl.openal.AL10.alListener3f(pname, v1, v2, v3);
}
public static void alSource3f(int source, int pname, float v1, float v2, float v3) {
org.lwjgl.openal.AL10.alSource3f(source, pname, v1, v2, v3);
}
public static void alSourceStop(int source) {
org.lwjgl.openal.AL10.alSourceStop(source);
}
public static final int AL_NO_ERROR = org.lwjgl.openal.AL10.AL_NO_ERROR;
public static final int AL_BUFFER = org.lwjgl.openal.AL10.AL_BUFFER;
public static final int AL_SOURCE_STATE = org.lwjgl.openal.AL10.AL_SOURCE_STATE;
public static final int AL_PLAYING = org.lwjgl.openal.AL10.AL_PLAYING;
public static final int AL_LOOPING = org.lwjgl.openal.AL10.AL_LOOPING;
public static final int AL_TRUE = org.lwjgl.openal.AL10.AL_TRUE;
public static final int AL_REFERENCE_DISTANCE = org.lwjgl.openal.AL10.AL_REFERENCE_DISTANCE;
public static final int AL_ROLLOFF_FACTOR = org.lwjgl.openal.AL10.AL_ROLLOFF_FACTOR;
public static final int AL_POSITION = org.lwjgl.openal.AL10.AL_POSITION;
public static void alGenBuffers(java.nio.IntBuffer buffers) {
org.lwjgl.openal.AL10.alGenBuffers(buffers);
}
public static void alGenSources(java.nio.IntBuffer sources) {
org.lwjgl.openal.AL10.alGenSources(sources);
}
public static void alBufferData(int buffer, int format, java.nio.ByteBuffer data, int freq) {
org.lwjgl.openal.AL10.alBufferData(buffer, format, data, freq);
}
public static void alSourcei(int source, int pname, int value) {
org.lwjgl.openal.AL10.alSourcei(source, pname, value);
}
public static int alGetSourcei(int source, int pname) {
return org.lwjgl.openal.AL10.alGetSourcei(source, pname);
}
public static String alGetString(int pname) {
return org.lwjgl.openal.AL10.alGetString(pname);
}
public static int alGetError() {
return org.lwjgl.openal.AL10.alGetError();
}
public static void alSourcef(int source, int pname, float value) {
org.lwjgl.openal.AL10.alSourcef(source, pname, value);
}
public static void alSourcePlay(int source) {
org.lwjgl.openal.AL10.alSourcePlay(source);
}
public static void alSourceStop(java.nio.IntBuffer sources) {
org.lwjgl.openal.AL10.alSourceStop(sources);
}
public static void alDeleteSources(java.nio.IntBuffer sources) {
org.lwjgl.openal.AL10.alDeleteSources(sources);
}
public static void alDeleteBuffers(java.nio.IntBuffer buffers) {
org.lwjgl.openal.AL10.alDeleteBuffers(buffers);
}
public static void alListener3f(int pname, float v1, float v2, float v3) {
org.lwjgl.openal.AL10.alListener3f(pname, v1, v2, v3);
}
public static void alSource3f(int source, int pname, float v1, float v2, float v3) {
org.lwjgl.openal.AL10.alSource3f(source, pname, v1, v2, v3);
}
public static void alSourceStop(int source) {
org.lwjgl.openal.AL10.alSourceStop(source);
}
}
+50 -51
View File
@@ -1,56 +1,55 @@
package org.lwjglx.openal;
public class ALC10 {
static ALCcontext alcContext;
public static final int ALC_FREQUENCY = org.lwjgl.openal.ALC10.ALC_FREQUENCY;
public static final int ALC_REFRESH = org.lwjgl.openal.ALC10.ALC_REFRESH;
public static final int ALC_SYNC = org.lwjgl.openal.ALC10.ALC_SYNC;
public static final int ALC_NO_ERROR = org.lwjgl.openal.ALC10.ALC_NO_ERROR;
public static final int ALC_DEFAULT_DEVICE_SPECIFIER = org.lwjgl.openal.ALC10.ALC_DEFAULT_DEVICE_SPECIFIER;
public static final int ALC_DEVICE_SPECIFIER = org.lwjgl.openal.ALC10.ALC_DEVICE_SPECIFIER;
public static int alcGetError(ALCdevice device) {
if (device == null) {
return org.lwjgl.openal.ALC10.alcGetError(AL.alcDevice.device);
}
return org.lwjgl.openal.ALC10.alcGetError(device.device);
}
public static java.lang.String alcGetString(ALCdevice device, int pname) {
if (device == null) {
return org.lwjgl.openal.ALC10.alcGetString(AL.alcDevice.device, pname);
}
return org.lwjgl.openal.ALC10.alcGetString(device.device, pname);
}
public static boolean alcIsExtensionPresent(ALCdevice device, java.lang.String extName) {
if (device == null) {
return org.lwjgl.openal.ALC10.alcIsExtensionPresent(AL.alcDevice.device, extName);
}
return org.lwjgl.openal.ALC10.alcIsExtensionPresent(device.device, extName);
}
public static ALCcontext alcCreateContext(ALCdevice device, java.nio.IntBuffer attrList) {
long alContextHandle = org.lwjgl.openal.ALC10.alcCreateContext(device.device, attrList);
alcContext = new ALCcontext(alContextHandle);
return alcContext;
}
public static ALCcontext alcGetCurrentContext() {
return alcContext;
}
public static ALCdevice alcGetContextsDevice(ALCcontext context) {
return AL.alcDevice;
}
public static void alcGetInteger(ALCdevice device, int pname, java.nio.IntBuffer integerdata) {
org.lwjgl.openal.ALC10.alcGetInteger(device.device, pname, integerdata);
}
static ALCcontext alcContext;
public static final int ALC_FREQUENCY = org.lwjgl.openal.ALC10.ALC_FREQUENCY;
public static final int ALC_REFRESH = org.lwjgl.openal.ALC10.ALC_REFRESH;
public static final int ALC_SYNC = org.lwjgl.openal.ALC10.ALC_SYNC;
public static final int ALC_NO_ERROR = org.lwjgl.openal.ALC10.ALC_NO_ERROR;
public static final int ALC_DEFAULT_DEVICE_SPECIFIER = org.lwjgl.openal.ALC10.ALC_DEFAULT_DEVICE_SPECIFIER;
public static final int ALC_DEVICE_SPECIFIER = org.lwjgl.openal.ALC10.ALC_DEVICE_SPECIFIER;
public static int alcGetError(ALCdevice device) {
if (device == null) {
return org.lwjgl.openal.ALC10.alcGetError(AL.alcDevice.device);
}
return org.lwjgl.openal.ALC10.alcGetError(device.device);
}
public static java.lang.String alcGetString(ALCdevice device, int pname) {
if (device == null) {
return org.lwjgl.openal.ALC10.alcGetString(AL.alcDevice.device, pname);
}
return org.lwjgl.openal.ALC10.alcGetString(device.device, pname);
}
public static boolean alcIsExtensionPresent(ALCdevice device, java.lang.String extName) {
if (device == null) {
return org.lwjgl.openal.ALC10.alcIsExtensionPresent(AL.alcDevice.device, extName);
}
return org.lwjgl.openal.ALC10.alcIsExtensionPresent(device.device, extName);
}
public static ALCcontext alcCreateContext(ALCdevice device, java.nio.IntBuffer attrList) {
long alContextHandle = org.lwjgl.openal.ALC10.alcCreateContext(device.device, attrList);
alcContext = new ALCcontext(alContextHandle);
return alcContext;
}
public static ALCcontext alcGetCurrentContext() {
return alcContext;
}
public static ALCdevice alcGetContextsDevice(ALCcontext context) {
return AL.alcDevice;
}
public static void alcGetInteger(ALCdevice device, int pname, java.nio.IntBuffer integerdata) {
org.lwjgl.openal.ALC10.alcGetInteger(device.device, pname, integerdata);
}
}
+53 -54
View File
@@ -32,7 +32,6 @@
package org.lwjglx.openal;
import java.nio.IntBuffer;
import org.lwjgl.BufferUtils;
/**
@@ -51,65 +50,65 @@ import org.lwjgl.BufferUtils;
*/
public final class ALCcontext {
/** Address of actual context */
final long context;
/** Address of actual context */
final long context;
/** Whether this context is valid */
private boolean valid;
/** Whether this context is valid */
private boolean valid;
/**
* Creates a new instance of ALCcontext
*
* @param context address of actual context
*/
ALCcontext(long context) {
this.context = context;
this.valid = true;
}
/**
* Creates a new instance of ALCcontext
*
* @param context address of actual context
*/
ALCcontext(long context) {
this.context = context;
this.valid = true;
}
/*
* @see java.lang.Object#equals(java.lang.Object)
*/
public boolean equals(Object context) {
if(context instanceof ALCcontext) {
return ((ALCcontext)context).context == this.context;
}
return super.equals(context);
}
/*
* @see java.lang.Object#equals(java.lang.Object)
*/
public boolean equals(Object context) {
if (context instanceof ALCcontext) {
return ((ALCcontext) context).context == this.context;
}
return super.equals(context);
}
/**
* Creates an attribute list in a ByteBuffer
* @param contextFrequency Frequency to add
* @param contextRefresh Refresh rate to add
* @param contextSynchronized Whether to synchronize the context
* @return
*/
static IntBuffer createAttributeList(int contextFrequency, int contextRefresh, int contextSynchronized) {
IntBuffer attribList = BufferUtils.createIntBuffer(7);
/**
* Creates an attribute list in a ByteBuffer
* @param contextFrequency Frequency to add
* @param contextRefresh Refresh rate to add
* @param contextSynchronized Whether to synchronize the context
* @return
*/
static IntBuffer createAttributeList(int contextFrequency, int contextRefresh, int contextSynchronized) {
IntBuffer attribList = BufferUtils.createIntBuffer(7);
attribList.put(ALC10.ALC_FREQUENCY);
attribList.put(contextFrequency);
attribList.put(ALC10.ALC_REFRESH);
attribList.put(contextRefresh);
attribList.put(ALC10.ALC_SYNC);
attribList.put(contextSynchronized);
attribList.put(0); //terminating int
attribList.put(ALC10.ALC_FREQUENCY);
attribList.put(contextFrequency);
attribList.put(ALC10.ALC_REFRESH);
attribList.put(contextRefresh);
attribList.put(ALC10.ALC_SYNC);
attribList.put(contextSynchronized);
attribList.put(0); // terminating int
return attribList;
}
return attribList;
}
/**
* Marks this context as invalid
*
*/
void setInvalid() {
valid = false;
}
/**
* Marks this context as invalid
*
*/
void setInvalid() {
valid = false;
}
/**
* @return true if this context is still valid
*/
public boolean isValid() {
return valid;
}
/**
* @return true if this context is still valid
*/
public boolean isValid() {
return valid;
}
}
+44 -45
View File
@@ -55,8 +55,8 @@ public final class ALCdevice {
/** Whether this device is valid */
private boolean valid;
/** List of contexts belonging to the device */
private final HashMap<Long, ALCcontext> contexts = new HashMap<Long, ALCcontext>();
/** List of contexts belonging to the device */
private final HashMap<Long, ALCcontext> contexts = new HashMap<Long, ALCcontext>();
/**
* Creates a new instance of ALCdevice
@@ -71,51 +71,50 @@ public final class ALCdevice {
/*
* @see java.lang.Object#equals(java.lang.Object)
*/
public boolean equals(Object device) {
if(device instanceof ALCdevice) {
return ((ALCdevice)device).device == this.device;
}
return super.equals(device);
}
public boolean equals(Object device) {
if (device instanceof ALCdevice) {
return ((ALCdevice) device).device == this.device;
}
return super.equals(device);
}
/**
* Adds a context to the device
*
* @param context context to add to the list of contexts for this device
*/
void addContext(ALCcontext context) {
synchronized (contexts) {
contexts.put(context.context, context);
}
}
/**
* Adds a context to the device
*
* @param context context to add to the list of contexts for this device
*/
void addContext(ALCcontext context) {
synchronized (contexts) {
contexts.put(context.context, context);
}
}
/**
* Remove context associated with device
*
* @param context Context to disassociate with device
*/
void removeContext(ALCcontext context) {
synchronized (contexts) {
contexts.remove(context.context);
}
}
/**
* Remove context associated with device
*
* @param context Context to disassociate with device
*/
void removeContext(ALCcontext context) {
synchronized (contexts) {
contexts.remove(context.context);
}
}
/**
* Marks this device and all of its contexts invalid
*/
void setInvalid() {
valid = false;
synchronized (contexts) {
for ( ALCcontext context : contexts.values() )
context.setInvalid();
}
contexts.clear();
}
/**
* Marks this device and all of its contexts invalid
*/
void setInvalid() {
valid = false;
synchronized (contexts) {
for (ALCcontext context : contexts.values()) context.setInvalid();
}
contexts.clear();
}
/**
* @return true if this device is still valid
*/
public boolean isValid() {
return valid;
}
/**
* @return true if this device is still valid
*/
public boolean isValid() {
return valid;
}
}
+135 -136
View File
@@ -1,143 +1,142 @@
package org.lwjglx.openal;
import java.nio.IntBuffer;
import org.lwjgl.openal.EXTEfx;
public class EFX10 {
public static final int AL_EFFECT_TYPE = EXTEfx.AL_EFFECT_TYPE;
public static final int AL_EFFECTSLOT_EFFECT = EXTEfx.AL_EFFECTSLOT_EFFECT;
public static final int AL_EFFECT_ECHO = EXTEfx.AL_EFFECT_ECHO;
public static final float AL_ECHO_MIN_DAMPING = EXTEfx.AL_ECHO_MIN_DAMPING;
public static final int AL_ECHO_DAMPING = EXTEfx.AL_ECHO_DAMPING;
public static final float AL_ECHO_MAX_DAMPING = EXTEfx.AL_ECHO_MAX_DAMPING;
public static final float AL_ECHO_MIN_DELAY = EXTEfx.AL_ECHO_MIN_DELAY;
public static final int AL_ECHO_DELAY = EXTEfx.AL_ECHO_DELAY;
public static final float AL_ECHO_MAX_DELAY = EXTEfx.AL_ECHO_MAX_DELAY;
public static final float AL_ECHO_MIN_FEEDBACK = EXTEfx.AL_ECHO_MIN_FEEDBACK;
public static final int AL_ECHO_FEEDBACK = EXTEfx.AL_ECHO_FEEDBACK;
public static final float AL_ECHO_MAX_FEEDBACK = EXTEfx.AL_ECHO_MAX_FEEDBACK;
public static final float AL_ECHO_MIN_LRDELAY = EXTEfx.AL_ECHO_MIN_LRDELAY;
public static final int AL_ECHO_LRDELAY = EXTEfx.AL_ECHO_LRDELAY;
public static final float AL_ECHO_MAX_LRDELAY = EXTEfx.AL_ECHO_MAX_LRDELAY;
public static final float AL_ECHO_MIN_SPREAD = EXTEfx.AL_ECHO_MIN_SPREAD;
public static final int AL_ECHO_SPREAD = EXTEfx.AL_ECHO_SPREAD;
public static final float AL_ECHO_MAX_SPREAD = EXTEfx.AL_ECHO_MAX_SPREAD;
public static final int AL_EFFECT_REVERB = EXTEfx.AL_EFFECT_REVERB;
public static final int AL_RING_MODULATOR_SINUSOID = EXTEfx.AL_RING_MODULATOR_SINUSOID;
public static final int AL_RING_MODULATOR_SAWTOOTH = EXTEfx.AL_RING_MODULATOR_SAWTOOTH;
public static final int AL_RING_MODULATOR_SQUARE = EXTEfx.AL_RING_MODULATOR_SQUARE;
public static final int AL_EFFECT_RING_MODULATOR = EXTEfx.AL_EFFECT_RING_MODULATOR;
public static final float AL_RING_MODULATOR_MAX_FREQUENCY = EXTEfx.AL_RING_MODULATOR_MAX_FREQUENCY;
public static final int AL_RING_MODULATOR_FREQUENCY = EXTEfx.AL_RING_MODULATOR_FREQUENCY;
public static final float AL_RING_MODULATOR_MIN_FREQUENCY = EXTEfx.AL_RING_MODULATOR_MIN_FREQUENCY;
public static final float AL_RING_MODULATOR_MAX_HIGHPASS_CUTOFF = EXTEfx.AL_RING_MODULATOR_MAX_HIGHPASS_CUTOFF;
public static final int AL_RING_MODULATOR_HIGHPASS_CUTOFF = EXTEfx.AL_RING_MODULATOR_HIGHPASS_CUTOFF;
public static final float AL_RING_MODULATOR_MIN_HIGHPASS_CUTOFF = EXTEfx.AL_RING_MODULATOR_MIN_HIGHPASS_CUTOFF;
public static final int AL_RING_MODULATOR_WAVEFORM = EXTEfx.AL_RING_MODULATOR_WAVEFORM;
public static final int AL_FILTER_TYPE = EXTEfx.AL_FILTER_TYPE;
public static final int AL_FILTER_LOWPASS = EXTEfx.AL_FILTER_LOWPASS;
public static final int AL_LOWPASS_GAIN = EXTEfx.AL_LOWPASS_GAIN;
public static final int AL_LOWPASS_GAINHF = EXTEfx.AL_LOWPASS_GAINHF;
public static final int AL_EFFECTSLOT_NULL = EXTEfx.AL_EFFECTSLOT_NULL;
public static final int AL_FILTER_NULL = EXTEfx.AL_FILTER_NULL;
public static final int AL_AUXILIARY_SEND_FILTER = EXTEfx.AL_AUXILIARY_SEND_FILTER;
public static final int AL_DIRECT_FILTER = EXTEfx.AL_DIRECT_FILTER;
public static final int ALC_MAX_AUXILIARY_SENDS = EXTEfx.ALC_MAX_AUXILIARY_SENDS;
public static final int ALC_EFX_MAJOR_VERSION = EXTEfx.ALC_EFX_MAJOR_VERSION;
public static final int AL_REVERB_DECAY_TIME = EXTEfx.AL_REVERB_DECAY_TIME;
public static final int AL_FILTER_HIGHPASS = EXTEfx.AL_FILTER_HIGHPASS;
public static final int AL_FILTER_BANDPASS = EXTEfx.AL_FILTER_BANDPASS;
public static final int AL_EFFECT_NULL = EXTEfx.AL_EFFECT_NULL;
public static final int AL_EFFECT_EAXREVERB = EXTEfx.AL_EFFECT_EAXREVERB;
public static final int AL_EFFECT_CHORUS = EXTEfx.AL_EFFECT_CHORUS;
public static final int AL_EFFECT_DISTORTION = EXTEfx.AL_EFFECT_DISTORTION;
public static final int AL_EFFECT_FLANGER = EXTEfx.AL_EFFECT_FLANGER;
public static final int AL_EFFECT_FREQUENCY_SHIFTER = EXTEfx.AL_EFFECT_FREQUENCY_SHIFTER;
public static final int AL_EFFECT_VOCAL_MORPHER = EXTEfx.AL_EFFECT_VOCAL_MORPHER;
public static final int AL_EFFECT_PITCH_SHIFTER = EXTEfx.AL_EFFECT_PITCH_SHIFTER;
public static final int AL_EFFECT_AUTOWAH = EXTEfx.AL_EFFECT_AUTOWAH;
public static final int AL_EFFECT_COMPRESSOR = EXTEfx.AL_EFFECT_COMPRESSOR;
public static final int AL_EFFECT_EQUALIZER = EXTEfx.AL_EFFECT_EQUALIZER;
public static int alGenAuxiliaryEffectSlots() {
return EXTEfx.alGenAuxiliaryEffectSlots();
}
public static int alGenFilters() {
return EXTEfx.alGenFilters();
}
public static void alDeleteFilters(int filter) {
EXTEfx.alDeleteFilters(filter);
}
public static void alFilteri(int filter, int param, int value) {
EXTEfx.alFilteri(filter, param, value);
}
public static void alFilterf(int filter, int param, float value) {
EXTEfx.alFilterf(filter, param, value);
}
public static float alGetFilterf(int filter, int param) {
return EXTEfx.alGetFilterf(filter, param);
}
public static int alGenEffects() {
return EXTEfx.alGenEffects();
}
public static void alDeleteEffects(int effect) {
EXTEfx.alDeleteAuxiliaryEffectSlots(effect);
}
public static void alDeleteAuxiliaryEffectSlots(int effectSlot) {
EXTEfx.alDeleteAuxiliaryEffectSlots(effectSlot);
}
public static void alEffecti(int effect, int param, int value) {
EXTEfx.alEffecti(effect, param, value);
}
public static float alGetEffectf(int effect, int param) {
return EXTEfx.alGetEffectf(effect, param);
}
public static int alGetEffecti(int effect, int param) {
return EXTEfx.alGetEffecti(effect, param);
}
public static void alEffectf(int effect, int param, float value) {
EXTEfx.alEffectf(effect, param, value);
}
public static void alAuxiliaryEffectSloti(int effectSlot, int param, int value) {
EXTEfx.alAuxiliaryEffectSloti(effectSlot, param, value);
}
public static void alGenAuxiliaryEffectSlots(IntBuffer effectSlots) {
EXTEfx.alGenAuxiliaryEffectSlots(effectSlots);
}
public static void alGenEffects(IntBuffer effects) {
EXTEfx.alGenEffects(effects);
}
public static void alDeleteEffects(IntBuffer effects) {
EXTEfx.alDeleteEffects(effects);
}
public static void alDeleteAuxiliaryEffectSlots(IntBuffer effectSlots) {
EXTEfx.alDeleteAuxiliaryEffectSlots(effectSlots);
}
public static void alGenFilters(IntBuffer filters) {
EXTEfx.alGenFilters(filters);
}
public static void alDeleteFilters(IntBuffer filters) {
EXTEfx.alDeleteFilters(filters);
}
public static final int AL_EFFECT_TYPE = EXTEfx.AL_EFFECT_TYPE;
public static final int AL_EFFECTSLOT_EFFECT = EXTEfx.AL_EFFECTSLOT_EFFECT;
public static final int AL_EFFECT_ECHO = EXTEfx.AL_EFFECT_ECHO;
public static final float AL_ECHO_MIN_DAMPING = EXTEfx.AL_ECHO_MIN_DAMPING;
public static final int AL_ECHO_DAMPING = EXTEfx.AL_ECHO_DAMPING;
public static final float AL_ECHO_MAX_DAMPING = EXTEfx.AL_ECHO_MAX_DAMPING;
public static final float AL_ECHO_MIN_DELAY = EXTEfx.AL_ECHO_MIN_DELAY;
public static final int AL_ECHO_DELAY = EXTEfx.AL_ECHO_DELAY;
public static final float AL_ECHO_MAX_DELAY = EXTEfx.AL_ECHO_MAX_DELAY;
public static final float AL_ECHO_MIN_FEEDBACK = EXTEfx.AL_ECHO_MIN_FEEDBACK;
public static final int AL_ECHO_FEEDBACK = EXTEfx.AL_ECHO_FEEDBACK;
public static final float AL_ECHO_MAX_FEEDBACK = EXTEfx.AL_ECHO_MAX_FEEDBACK;
public static final float AL_ECHO_MIN_LRDELAY = EXTEfx.AL_ECHO_MIN_LRDELAY;
public static final int AL_ECHO_LRDELAY = EXTEfx.AL_ECHO_LRDELAY;
public static final float AL_ECHO_MAX_LRDELAY = EXTEfx.AL_ECHO_MAX_LRDELAY;
public static final float AL_ECHO_MIN_SPREAD = EXTEfx.AL_ECHO_MIN_SPREAD;
public static final int AL_ECHO_SPREAD = EXTEfx.AL_ECHO_SPREAD;
public static final float AL_ECHO_MAX_SPREAD = EXTEfx.AL_ECHO_MAX_SPREAD;
public static final int AL_EFFECT_REVERB = EXTEfx.AL_EFFECT_REVERB;
public static final int AL_RING_MODULATOR_SINUSOID = EXTEfx.AL_RING_MODULATOR_SINUSOID;
public static final int AL_RING_MODULATOR_SAWTOOTH = EXTEfx.AL_RING_MODULATOR_SAWTOOTH;
public static final int AL_RING_MODULATOR_SQUARE = EXTEfx.AL_RING_MODULATOR_SQUARE;
public static final int AL_EFFECT_RING_MODULATOR = EXTEfx.AL_EFFECT_RING_MODULATOR;
public static final float AL_RING_MODULATOR_MAX_FREQUENCY = EXTEfx.AL_RING_MODULATOR_MAX_FREQUENCY;
public static final int AL_RING_MODULATOR_FREQUENCY = EXTEfx.AL_RING_MODULATOR_FREQUENCY;
public static final float AL_RING_MODULATOR_MIN_FREQUENCY = EXTEfx.AL_RING_MODULATOR_MIN_FREQUENCY;
public static final float AL_RING_MODULATOR_MAX_HIGHPASS_CUTOFF = EXTEfx.AL_RING_MODULATOR_MAX_HIGHPASS_CUTOFF;
public static final int AL_RING_MODULATOR_HIGHPASS_CUTOFF = EXTEfx.AL_RING_MODULATOR_HIGHPASS_CUTOFF;
public static final float AL_RING_MODULATOR_MIN_HIGHPASS_CUTOFF = EXTEfx.AL_RING_MODULATOR_MIN_HIGHPASS_CUTOFF;
public static final int AL_RING_MODULATOR_WAVEFORM = EXTEfx.AL_RING_MODULATOR_WAVEFORM;
public static final int AL_FILTER_TYPE = EXTEfx.AL_FILTER_TYPE;
public static final int AL_FILTER_LOWPASS = EXTEfx.AL_FILTER_LOWPASS;
public static final int AL_LOWPASS_GAIN = EXTEfx.AL_LOWPASS_GAIN;
public static final int AL_LOWPASS_GAINHF = EXTEfx.AL_LOWPASS_GAINHF;
public static final int AL_EFFECTSLOT_NULL = EXTEfx.AL_EFFECTSLOT_NULL;
public static final int AL_FILTER_NULL = EXTEfx.AL_FILTER_NULL;
public static final int AL_AUXILIARY_SEND_FILTER = EXTEfx.AL_AUXILIARY_SEND_FILTER;
public static final int AL_DIRECT_FILTER = EXTEfx.AL_DIRECT_FILTER;
public static final int ALC_MAX_AUXILIARY_SENDS = EXTEfx.ALC_MAX_AUXILIARY_SENDS;
public static final int ALC_EFX_MAJOR_VERSION = EXTEfx.ALC_EFX_MAJOR_VERSION;
public static final int AL_REVERB_DECAY_TIME = EXTEfx.AL_REVERB_DECAY_TIME;
public static final int AL_FILTER_HIGHPASS = EXTEfx.AL_FILTER_HIGHPASS;
public static final int AL_FILTER_BANDPASS = EXTEfx.AL_FILTER_BANDPASS;
public static final int AL_EFFECT_NULL = EXTEfx.AL_EFFECT_NULL;
public static final int AL_EFFECT_EAXREVERB = EXTEfx.AL_EFFECT_EAXREVERB;
public static final int AL_EFFECT_CHORUS = EXTEfx.AL_EFFECT_CHORUS;
public static final int AL_EFFECT_DISTORTION = EXTEfx.AL_EFFECT_DISTORTION;
public static final int AL_EFFECT_FLANGER = EXTEfx.AL_EFFECT_FLANGER;
public static final int AL_EFFECT_FREQUENCY_SHIFTER = EXTEfx.AL_EFFECT_FREQUENCY_SHIFTER;
public static final int AL_EFFECT_VOCAL_MORPHER = EXTEfx.AL_EFFECT_VOCAL_MORPHER;
public static final int AL_EFFECT_PITCH_SHIFTER = EXTEfx.AL_EFFECT_PITCH_SHIFTER;
public static final int AL_EFFECT_AUTOWAH = EXTEfx.AL_EFFECT_AUTOWAH;
public static final int AL_EFFECT_COMPRESSOR = EXTEfx.AL_EFFECT_COMPRESSOR;
public static final int AL_EFFECT_EQUALIZER = EXTEfx.AL_EFFECT_EQUALIZER;
public static int alGenAuxiliaryEffectSlots() {
return EXTEfx.alGenAuxiliaryEffectSlots();
}
public static int alGenFilters() {
return EXTEfx.alGenFilters();
}
public static void alDeleteFilters(int filter) {
EXTEfx.alDeleteFilters(filter);
}
public static void alFilteri(int filter, int param, int value) {
EXTEfx.alFilteri(filter, param, value);
}
public static void alFilterf(int filter, int param, float value) {
EXTEfx.alFilterf(filter, param, value);
}
public static float alGetFilterf(int filter, int param) {
return EXTEfx.alGetFilterf(filter, param);
}
public static int alGenEffects() {
return EXTEfx.alGenEffects();
}
public static void alDeleteEffects(int effect) {
EXTEfx.alDeleteAuxiliaryEffectSlots(effect);
}
public static void alDeleteAuxiliaryEffectSlots(int effectSlot) {
EXTEfx.alDeleteAuxiliaryEffectSlots(effectSlot);
}
public static void alEffecti(int effect, int param, int value) {
EXTEfx.alEffecti(effect, param, value);
}
public static float alGetEffectf(int effect, int param) {
return EXTEfx.alGetEffectf(effect, param);
}
public static int alGetEffecti(int effect, int param) {
return EXTEfx.alGetEffecti(effect, param);
}
public static void alEffectf(int effect, int param, float value) {
EXTEfx.alEffectf(effect, param, value);
}
public static void alAuxiliaryEffectSloti(int effectSlot, int param, int value) {
EXTEfx.alAuxiliaryEffectSloti(effectSlot, param, value);
}
public static void alGenAuxiliaryEffectSlots(IntBuffer effectSlots) {
EXTEfx.alGenAuxiliaryEffectSlots(effectSlots);
}
public static void alGenEffects(IntBuffer effects) {
EXTEfx.alGenEffects(effects);
}
public static void alDeleteEffects(IntBuffer effects) {
EXTEfx.alDeleteEffects(effects);
}
public static void alDeleteAuxiliaryEffectSlots(IntBuffer effectSlots) {
EXTEfx.alDeleteAuxiliaryEffectSlots(effectSlots);
}
public static void alGenFilters(IntBuffer filters) {
EXTEfx.alGenFilters(filters);
}
public static void alDeleteFilters(IntBuffer filters) {
EXTEfx.alDeleteFilters(filters);
}
}
+171 -173
View File
@@ -19,190 +19,188 @@ import org.lwjgl.openal.ALC;
*/
public final class EFXUtil {
/** Constant for testSupportGeneric to check an effect. */
private static final int EFFECT = 1111;
/** Constant for testSupportGeneric to check a filter. */
private static final int FILTER = 2222;
/** Constant for testSupportGeneric to check an effect. */
private static final int EFFECT = 1111;
/** Constant for testSupportGeneric to check a filter. */
private static final int FILTER = 2222;
/** Utility class, hidden contructor. */
private EFXUtil() {
}
/** Utility class, hidden contructor. */
private EFXUtil() {}
/**
* Checks if OpenAL implementation is loaded and supports AL_EXT_EFX.
*
* @return True if AL_EXT_EFX is supported, false if not.
*
* @throws org.lwjgl.openal.OpenALException
* If OpenAL has not been created yet.
*/
public static boolean isEfxSupported() {
return ALC.getCapabilities().ALC_EXT_EFX;
}
/**
* Checks if OpenAL implementation is loaded and supports AL_EXT_EFX.
*
* @return True if AL_EXT_EFX is supported, false if not.
*
* @throws org.lwjgl.openal.OpenALException
* If OpenAL has not been created yet.
*/
public static boolean isEfxSupported() {
return ALC.getCapabilities().ALC_EXT_EFX;
}
/**
* Tests OpenAL to see whether the given effect type is supported. This is done by creating an
* effect of the given type. If creation succeeds the effect is supported.
*
* @param effectType Type of effect whose support is to be tested, e.g. AL_EFFECT_REVERB.
*
* @return True if it is supported, false if not.
*
* @throws org.lwjgl.openal.OpenALException
* If the request fails due to an AL_OUT_OF_MEMORY error or OpenAL has
* not been created yet.
* @throws IllegalArgumentException effectType is not a valid effect type.
*/
public static boolean isEffectSupported(int effectType) {
// Make sure type is a real effect.
switch ( effectType ) {
case AL_EFFECT_NULL:
case AL_EFFECT_EAXREVERB:
case AL_EFFECT_REVERB:
case AL_EFFECT_CHORUS:
case AL_EFFECT_DISTORTION:
case AL_EFFECT_ECHO:
case AL_EFFECT_FLANGER:
case AL_EFFECT_FREQUENCY_SHIFTER:
case AL_EFFECT_VOCAL_MORPHER:
case AL_EFFECT_PITCH_SHIFTER:
case AL_EFFECT_RING_MODULATOR:
case AL_EFFECT_AUTOWAH:
case AL_EFFECT_COMPRESSOR:
case AL_EFFECT_EQUALIZER:
break;
default:
throw new IllegalArgumentException("Unknown or invalid effect type: " + effectType);
}
/**
* Tests OpenAL to see whether the given effect type is supported. This is done by creating an
* effect of the given type. If creation succeeds the effect is supported.
*
* @param effectType Type of effect whose support is to be tested, e.g. AL_EFFECT_REVERB.
*
* @return True if it is supported, false if not.
*
* @throws org.lwjgl.openal.OpenALException
* If the request fails due to an AL_OUT_OF_MEMORY error or OpenAL has
* not been created yet.
* @throws IllegalArgumentException effectType is not a valid effect type.
*/
public static boolean isEffectSupported(int effectType) {
// Make sure type is a real effect.
switch (effectType) {
case AL_EFFECT_NULL:
case AL_EFFECT_EAXREVERB:
case AL_EFFECT_REVERB:
case AL_EFFECT_CHORUS:
case AL_EFFECT_DISTORTION:
case AL_EFFECT_ECHO:
case AL_EFFECT_FLANGER:
case AL_EFFECT_FREQUENCY_SHIFTER:
case AL_EFFECT_VOCAL_MORPHER:
case AL_EFFECT_PITCH_SHIFTER:
case AL_EFFECT_RING_MODULATOR:
case AL_EFFECT_AUTOWAH:
case AL_EFFECT_COMPRESSOR:
case AL_EFFECT_EQUALIZER:
break;
default:
throw new IllegalArgumentException("Unknown or invalid effect type: " + effectType);
}
return testSupportGeneric(EFFECT, effectType);
}
return testSupportGeneric(EFFECT, effectType);
}
/**
* Tests OpenAL to see whether the given filter type is supported. This is done by creating a
* filter of the given type. If creation succeeds the filter is supported.
*
* @param filterType Type of filter whose support is to be tested, e.g. AL_FILTER_LOWPASS.
*
* @return True if it is supported, false if not.
*
* @throws org.lwjgl.openal.OpenALException
* If the request fails due to an AL_OUT_OF_MEMORY error or OpenAL has
* not been created yet.
* @throws IllegalArgumentException filterType is not a valid filter type.
*/
public static boolean isFilterSupported(int filterType) {
// Make sure type is a real filter.
switch ( filterType ) {
case AL_FILTER_NULL:
case AL_FILTER_LOWPASS:
case AL_FILTER_HIGHPASS:
case AL_FILTER_BANDPASS:
break;
default:
throw new IllegalArgumentException("Unknown or invalid filter type: " + filterType);
}
/**
* Tests OpenAL to see whether the given filter type is supported. This is done by creating a
* filter of the given type. If creation succeeds the filter is supported.
*
* @param filterType Type of filter whose support is to be tested, e.g. AL_FILTER_LOWPASS.
*
* @return True if it is supported, false if not.
*
* @throws org.lwjgl.openal.OpenALException
* If the request fails due to an AL_OUT_OF_MEMORY error or OpenAL has
* not been created yet.
* @throws IllegalArgumentException filterType is not a valid filter type.
*/
public static boolean isFilterSupported(int filterType) {
// Make sure type is a real filter.
switch (filterType) {
case AL_FILTER_NULL:
case AL_FILTER_LOWPASS:
case AL_FILTER_HIGHPASS:
case AL_FILTER_BANDPASS:
break;
default:
throw new IllegalArgumentException("Unknown or invalid filter type: " + filterType);
}
return testSupportGeneric(FILTER, filterType);
}
return testSupportGeneric(FILTER, filterType);
}
/**
* Generic test function to see if an EFX object supports a given kind of type. Works for
* effects and filters.
*
* @param objectType Type of object to test. Must be either EFXUtil.EFFECT or EFXUtil.FILTER.
* @param typeValue OpenAL type the object should be tested for support, e.g. AL_FILTER_LOWPASS
* or AL_EFFECT_REVERB.
*
* @return True if object supports typeValue, false else.
*/
private static boolean testSupportGeneric(int objectType, int typeValue) {
// Check for supported objectType.
switch ( objectType ) {
case EFFECT:
case FILTER:
break;
default:
throw new IllegalArgumentException("Invalid objectType: " + objectType);
}
/**
* Generic test function to see if an EFX object supports a given kind of type. Works for
* effects and filters.
*
* @param objectType Type of object to test. Must be either EFXUtil.EFFECT or EFXUtil.FILTER.
* @param typeValue OpenAL type the object should be tested for support, e.g. AL_FILTER_LOWPASS
* or AL_EFFECT_REVERB.
*
* @return True if object supports typeValue, false else.
*/
private static boolean testSupportGeneric(int objectType, int typeValue) {
// Check for supported objectType.
switch (objectType) {
case EFFECT:
case FILTER:
break;
default:
throw new IllegalArgumentException("Invalid objectType: " + objectType);
}
boolean supported = false;
if ( isEfxSupported() ) {
boolean supported = false;
if (isEfxSupported()) {
// Try to create object in order to check AL's response.
alGetError();
int genError;
int testObject = 0;
try {
switch ( objectType ) { // Create object based on type
case EFFECT:
testObject = alGenEffects();
break;
case FILTER:
testObject = alGenFilters();
break;
default:
throw new IllegalArgumentException("Invalid objectType: " + objectType);
}
genError = alGetError();
} catch (OpenALException debugBuildException) {
// Hack because OpenALException hides the original error code (short of parsing the
// error message String which would break if it gets changed).
if ( debugBuildException.getMessage().contains("AL_OUT_OF_MEMORY") ) {
genError = AL_OUT_OF_MEMORY;
} else {
genError = AL_INVALID_OPERATION;
}
}
// Try to create object in order to check AL's response.
alGetError();
int genError;
int testObject = 0;
try {
switch (objectType) { // Create object based on type
case EFFECT:
testObject = alGenEffects();
break;
case FILTER:
testObject = alGenFilters();
break;
default:
throw new IllegalArgumentException("Invalid objectType: " + objectType);
}
genError = alGetError();
} catch (OpenALException debugBuildException) {
// Hack because OpenALException hides the original error code (short of parsing the
// error message String which would break if it gets changed).
if (debugBuildException.getMessage().contains("AL_OUT_OF_MEMORY")) {
genError = AL_OUT_OF_MEMORY;
} else {
genError = AL_INVALID_OPERATION;
}
}
if ( genError == AL_NO_ERROR ) {
// Successfully created, now try to set type.
alGetError();
int setError;
try {
switch ( objectType ) { // Set based on object type
case EFFECT:
alEffecti(testObject, AL_EFFECT_TYPE, typeValue);
break;
case FILTER:
alFilteri(testObject, AL_FILTER_TYPE, typeValue);
break;
default:
throw new IllegalArgumentException("Invalid objectType: " + objectType);
}
setError = alGetError();
} catch (OpenALException debugBuildException) {
// Hack because OpenALException hides the original error code (short of parsing
// the error message String which would break when it gets changed).
setError = AL_INVALID_VALUE;
}
if (genError == AL_NO_ERROR) {
// Successfully created, now try to set type.
alGetError();
int setError;
try {
switch (objectType) { // Set based on object type
case EFFECT:
alEffecti(testObject, AL_EFFECT_TYPE, typeValue);
break;
case FILTER:
alFilteri(testObject, AL_FILTER_TYPE, typeValue);
break;
default:
throw new IllegalArgumentException("Invalid objectType: " + objectType);
}
setError = alGetError();
} catch (OpenALException debugBuildException) {
// Hack because OpenALException hides the original error code (short of parsing
// the error message String which would break when it gets changed).
setError = AL_INVALID_VALUE;
}
if ( setError == AL_NO_ERROR ) {
supported = true;
}
if (setError == AL_NO_ERROR) {
supported = true;
}
// Cleanup
try {
switch ( objectType ) { // Set based on object type
case EFFECT:
alDeleteEffects(testObject);
break;
case FILTER:
alDeleteFilters(testObject);
break;
default:
throw new IllegalArgumentException("Invalid objectType: " + objectType);
}
} catch (OpenALException debugBuildException) {
// Don't care about cleanup errors.
}
// Cleanup
try {
switch (objectType) { // Set based on object type
case EFFECT:
alDeleteEffects(testObject);
break;
case FILTER:
alDeleteFilters(testObject);
break;
default:
throw new IllegalArgumentException("Invalid objectType: " + objectType);
}
} catch (OpenALException debugBuildException) {
// Don't care about cleanup errors.
}
} else if ( genError == AL_OUT_OF_MEMORY ) {
throw new OpenALException(AL10.alGetString(genError));
}
}
} else if (genError == AL_OUT_OF_MEMORY) {
throw new OpenALException(AL10.alGetString(genError));
}
}
return supported;
}
}
return supported;
}
}
@@ -1,31 +1,31 @@
/*
/*
* Copyright (c) 2002-2008 LWJGL Project
* All rights reserved.
*
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* * Neither the name of 'LWJGL' nor the names of
* its contributors may be used to endorse or promote products derived
* * Neither the name of 'LWJGL' nor the names of
* its contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
@@ -35,51 +35,51 @@ package org.lwjglx.openal;
* <br>
* Thrown by the debug build library of the LWJGL if any OpenAL operation
* causes an error.
*
*
* @author Brian Matzon <[email protected]>
* @version $Revision$
* $Id$
*/
public class OpenALException extends RuntimeException {
private static final long serialVersionUID = 1L;
private static final long serialVersionUID = 1L;
/**
* Constructor for OpenALException.
*/
public OpenALException() {
super();
}
/**
* Constructor for OpenALException.
*/
public OpenALException() {
super();
}
/**
* Constructor that takes an AL error number
*/
public OpenALException(int error_code) {
super("OpenAL error: " + org.lwjgl.openal.AL10.alGetString(error_code) + " (" + error_code + ")");
}
/**
* Constructor that takes an AL error number
*/
public OpenALException(int error_code) {
super("OpenAL error: " + org.lwjgl.openal.AL10.alGetString(error_code) + " (" + error_code + ")");
}
/**
* Constructor for OpenALException.
* @param message
*/
public OpenALException(String message) {
super(message);
}
/**
* Constructor for OpenALException.
* @param message
*/
public OpenALException(String message) {
super(message);
}
/**
* Constructor for OpenALException.
* @param message
* @param cause
*/
public OpenALException(String message, Throwable cause) {
super(message, cause);
}
/**
* Constructor for OpenALException.
* @param message
* @param cause
*/
public OpenALException(String message, Throwable cause) {
super(message, cause);
}
/**
* Constructor for OpenALException.
* @param cause
*/
public OpenALException(Throwable cause) {
super(cause);
}
/**
* Constructor for OpenALException.
* @param cause
*/
public OpenALException(Throwable cause) {
super(cause);
}
}
+36 -41
View File
@@ -31,7 +31,6 @@
*/
package org.lwjglx.openal;
/**
* Simple utility class for checking AL/ALC errors
*
@@ -39,48 +38,44 @@ package org.lwjglx.openal;
* @author Brian Matzon <[email protected]>
* @version $Revision$
*/
public final class Util {
/** No c'tor */
private Util() {
}
/** No c'tor */
private Util() {}
/**
* Checks for any ALC errors and throws an unchecked exception on errors
* @param device Device for which to check ALC errors
*/
public static void checkALCError(ALCdevice device) {
int err = ALC10.alcGetError(device);
if (err != ALC10.ALC_NO_ERROR)
throw new OpenALException(ALC10.alcGetString(AL.getDevice(), err));
}
/**
* Checks for any AL errors and throws an unchecked exception on errors
*/
public static void checkALError() {
int err = AL10.alGetError();
if (err != AL10.AL_NO_ERROR)
throw new OpenALException(err);
}
/**
* Checks for any ALC errors and throws an unchecked exception on errors
* @param device Device for which to check ALC errors
*/
public static void checkALCError(ALCdevice device) {
int err = ALC10.alcGetError(device);
if (err != ALC10.ALC_NO_ERROR) throw new OpenALException(ALC10.alcGetString(AL.getDevice(), err));
}
/**
* Checks for a valid device
* @param device ALCdevice to check the validity of
*/
public static void checkALCValidDevice(ALCdevice device) {
if(!device.isValid()) {
throw new OpenALException("Invalid device: " + device);
}
}
/**
* Checks for any AL errors and throws an unchecked exception on errors
*/
public static void checkALError() {
int err = AL10.alGetError();
if (err != AL10.AL_NO_ERROR) throw new OpenALException(err);
}
/**
* Checks for a valid context
* @param context ALCcontext to check the validity of
*/
public static void checkALCValidContext(ALCcontext context) {
if(!context.isValid()) {
throw new OpenALException("Invalid context: " + context);
}
}
/**
* Checks for a valid device
* @param device ALCdevice to check the validity of
*/
public static void checkALCValidDevice(ALCdevice device) {
if (!device.isValid()) {
throw new OpenALException("Invalid device: " + device);
}
}
/**
* Checks for a valid context
* @param context ALCcontext to check the validity of
*/
public static void checkALCValidContext(ALCcontext context) {
if (!context.isValid()) {
throw new OpenALException("Invalid context: " + context);
}
}
}
+54 -117
View File
@@ -31,165 +31,102 @@
*/
package org.lwjglx.opengl;
import org.lwjglx.LWJGLException;
import org.lwjglx.PointerBuffer;
import java.awt.*;
import java.awt.event.ComponentEvent;
import java.awt.event.ComponentListener;
import java.awt.event.HierarchyEvent;
import java.awt.event.HierarchyListener;
import org.lwjglx.LWJGLException;
import org.lwjglx.PointerBuffer;
public class AWTGLCanvas extends Canvas implements Drawable, ComponentListener, HierarchyListener {
private static final long serialVersionUID = 1L;
private static final long serialVersionUID = 1L;
public void setPixelFormat(final PixelFormatLWJGL pf) throws LWJGLException {
throw new UnsupportedOperationException();
}
public void setPixelFormat(final PixelFormatLWJGL pf) throws LWJGLException {
throw new UnsupportedOperationException();
}
public void setPixelFormat(final PixelFormatLWJGL pf, final ContextAttribs attribs) throws LWJGLException {
throw new UnsupportedOperationException();
}
public void setPixelFormat(final PixelFormatLWJGL pf, final ContextAttribs attribs) throws LWJGLException {
throw new UnsupportedOperationException();
}
public PixelFormatLWJGL getPixelFormat() {
return null;
}
public PixelFormatLWJGL getPixelFormat() {
return null;
}
public ContextGL getContext() {
return null;
}
public ContextGL getContext() {
return null;
}
public ContextGL createSharedContext() throws LWJGLException {
return null;
}
public ContextGL createSharedContext() throws LWJGLException {
return null;
}
public void checkGLError() {
}
public void checkGLError() {}
public void initContext(final float r, final float g, final float b) {
}
public void initContext(final float r, final float g, final float b) {}
public AWTGLCanvas() throws LWJGLException {
}
public AWTGLCanvas() throws LWJGLException {}
public AWTGLCanvas(PixelFormat pixel_format) throws LWJGLException {
}
public AWTGLCanvas(PixelFormat pixel_format) throws LWJGLException {}
public AWTGLCanvas(GraphicsDevice device, PixelFormat pixel_format) throws LWJGLException {
}
public AWTGLCanvas(GraphicsDevice device, PixelFormat pixel_format) throws LWJGLException {}
public AWTGLCanvas(GraphicsDevice device, PixelFormat pixel_format, Drawable drawable) throws LWJGLException {
}
public AWTGLCanvas(GraphicsDevice device, PixelFormat pixel_format, Drawable drawable) throws LWJGLException {}
public AWTGLCanvas(GraphicsDevice device, PixelFormat pixel_format, Drawable drawable, ContextAttribs attribs) throws LWJGLException {
}
public AWTGLCanvas(GraphicsDevice device, PixelFormat pixel_format, Drawable drawable, ContextAttribs attribs)
throws LWJGLException {}
public void addNotify() {
}
public void addNotify() {}
public void removeNotify() {
}
public void removeNotify() {}
public void setSwapInterval(int swap_interval) {
}
public void setSwapInterval(int swap_interval) {}
public void setVSyncEnabled(boolean enabled) {
}
public void setVSyncEnabled(boolean enabled) {}
public void swapBuffers() throws LWJGLException {
}
public void swapBuffers() throws LWJGLException {}
public boolean isCurrent() throws LWJGLException {
return false;
}
public boolean isCurrent() throws LWJGLException {
return false;
}
public void makeCurrent() throws LWJGLException {
}
public void makeCurrent() throws LWJGLException {}
public void releaseContext() throws LWJGLException {
}
public void releaseContext() throws LWJGLException {}
public final void destroy() {
}
public final void destroy() {}
public final void setCLSharingProperties(final PointerBuffer properties) throws LWJGLException {
}
public final void setCLSharingProperties(final PointerBuffer properties) throws LWJGLException {}
protected void initGL() {
}
protected void initGL() {}
protected void paintGL() {
}
protected void paintGL() {}
public final void paint(Graphics g) {
}
public final void paint(Graphics g) {}
protected void exceptionOccurred(LWJGLException exception) {
}
protected void exceptionOccurred(LWJGLException exception) {}
public void update(Graphics g) {
}
public void update(Graphics g) {}
public void componentShown(ComponentEvent e) {
}
public void componentShown(ComponentEvent e) {}
public void componentHidden(ComponentEvent e) {
}
public void componentHidden(ComponentEvent e) {}
public void componentResized(ComponentEvent e) {
}
public void componentResized(ComponentEvent e) {}
public void componentMoved(ComponentEvent e) {
}
public void componentMoved(ComponentEvent e) {}
public void setLocation(int x, int y) {
}
public void setLocation(int x, int y) {}
public void setLocation(Point p) {
}
public void setLocation(Point p) {}
public void setSize(Dimension d) {
}
public void setSize(Dimension d) {}
public void setSize(int width, int height) {
}
public void setSize(int width, int height) {}
public void setBounds(int x, int y, int width, int height) {
}
public void setBounds(int x, int y, int width, int height) {}
public void hierarchyChanged(HierarchyEvent e) {
}
}
public void hierarchyChanged(HierarchyEvent e) {}
}
+5 -6
View File
@@ -39,12 +39,11 @@ import org.lwjglx.LWJGLException;
*/
interface Context {
boolean isCurrent() throws LWJGLException;
boolean isCurrent() throws LWJGLException;
void makeCurrent() throws LWJGLException;
void makeCurrent() throws LWJGLException;
void releaseCurrent() throws LWJGLException;
void releaseCurrent() throws LWJGLException;
void releaseDrawable() throws LWJGLException;
}
void releaseDrawable() throws LWJGLException;
}
@@ -33,80 +33,75 @@ package org.lwjglx.opengl;
public final class ContextAttribs {
public ContextAttribs() {
}
public ContextAttribs() {}
public ContextAttribs(final int majorVersion, final int minorVersion) {
}
public ContextAttribs(final int majorVersion, final int minorVersion) {}
public int getMajorVersion() {
return 0;
}
public int getMajorVersion() {
return 0;
}
public int getMinorVersion() {
return 0;
}
public int getMinorVersion() {
return 0;
}
public int getLayerPlane() {
return 0;
}
public int getLayerPlane() {
return 0;
}
public boolean isDebug() {
return false;
}
public boolean isDebug() {
return false;
}
public boolean isForwardCompatible() {
return false;
}
public boolean isForwardCompatible() {
return false;
}
public boolean isProfileCore() {
return false;
}
public boolean isProfileCore() {
return false;
}
public boolean isProfileCompatibility() {
return false;
}
public boolean isProfileCompatibility() {
return false;
}
public boolean isProfileES() {
return false;
}
public boolean isProfileES() {
return false;
}
public ContextAttribs withLayer(final int layerPlane) {
return null;
}
public ContextAttribs withLayer(final int layerPlane) {
return null;
}
public ContextAttribs withDebug(final boolean debug) {
return null;
}
public ContextAttribs withDebug(final boolean debug) {
return null;
}
public ContextAttribs withForwardCompatible(final boolean forwardCompatible) {
return null;
}
public ContextAttribs withForwardCompatible(final boolean forwardCompatible) {
return null;
}
public ContextAttribs withProfileCore(final boolean profileCore) {
return null;
}
public ContextAttribs withProfileCore(final boolean profileCore) {
return null;
}
public ContextAttribs withProfileCompatibility(final boolean profileCompatibility) {
return null;
}
public ContextAttribs withProfileCompatibility(final boolean profileCompatibility) {
return null;
}
public ContextAttribs withProfileES(final boolean profileES) {
return null;
}
public ContextAttribs withProfileES(final boolean profileES) {
return null;
}
public ContextAttribs withLoseContextOnReset(final boolean loseContextOnReset) {
return null;
}
public ContextAttribs withLoseContextOnReset(final boolean loseContextOnReset) {
return null;
}
public ContextAttribs withContextResetIsolation(final boolean contextResetIsolation) {
return null;
}
public ContextAttribs withContextResetIsolation(final boolean contextResetIsolation) {
return null;
}
public String toString() {
return null;
}
}
public String toString() {
return null;
}
}
@@ -3,400 +3,401 @@ package org.lwjglx.opengl;
import java.lang.reflect.Field;
public class ContextCapabilities {
org.lwjgl.opengl.ContextCapabilities cap = org.lwjgl.opengl.GLContext.createFromCurrent().getCapabilities();
public ContextCapabilities() {
Field[] fields = org.lwjgl.opengl.ContextCapabilities.class.getFields();
try {
for ( Field field : fields ) {
String name = field.getName();
if (name.startsWith("GL_") || name.startsWith("OpenGL")) {
boolean value = field.getBoolean(cap);
try {
Field f = this.getClass().getField(name);
f.setBoolean(this, value);
} catch (Exception e) {
}
}
}
} catch (Exception e) {
System.out.println(e);
}
}
public boolean GL_AMD_blend_minmax_factor;
public boolean GL_AMD_conservative_depth;
public boolean GL_AMD_debug_output;
public boolean GL_AMD_depth_clamp_separate;
public boolean GL_AMD_draw_buffers_blend;
public boolean GL_AMD_interleaved_elements;
public boolean GL_AMD_multi_draw_indirect;
public boolean GL_AMD_name_gen_delete;
public boolean GL_AMD_performance_monitor;
public boolean GL_AMD_pinned_memory;
public boolean GL_AMD_query_buffer_object;
public boolean GL_AMD_sample_positions;
public boolean GL_AMD_seamless_cubemap_per_texture;
public boolean GL_AMD_shader_atomic_counter_ops;
public boolean GL_AMD_shader_stencil_export;
public boolean GL_AMD_shader_trinary_minmax;
public boolean GL_AMD_sparse_texture;
public boolean GL_AMD_stencil_operation_extended;
public boolean GL_AMD_texture_texture4;
public boolean GL_AMD_transform_feedback3_lines_triangles;
public boolean GL_AMD_vertex_shader_layer;
public boolean GL_AMD_vertex_shader_tessellator;
public boolean GL_AMD_vertex_shader_viewport_index;
public boolean GL_APPLE_aux_depth_stencil;
public boolean GL_APPLE_client_storage;
public boolean GL_APPLE_element_array;
public boolean GL_APPLE_fence;
public boolean GL_APPLE_float_pixels;
public boolean GL_APPLE_flush_buffer_range;
public boolean GL_APPLE_object_purgeable;
public boolean GL_APPLE_packed_pixels;
public boolean GL_APPLE_rgb_422;
public boolean GL_APPLE_row_bytes;
public boolean GL_APPLE_texture_range;
public boolean GL_APPLE_vertex_array_object;
public boolean GL_APPLE_vertex_array_range;
public boolean GL_APPLE_vertex_program_evaluators;
public boolean GL_APPLE_ycbcr_422;
public boolean GL_ARB_ES2_compatibility;
public boolean GL_ARB_ES3_compatibility;
public boolean GL_ARB_arrays_of_arrays;
public boolean GL_ARB_base_instance;
public boolean GL_ARB_bindless_texture;
public boolean GL_ARB_blend_func_extended;
public boolean GL_ARB_buffer_storage;
public boolean GL_ARB_cl_event;
public boolean GL_ARB_clear_buffer_object;
public boolean GL_ARB_clear_texture;
public boolean GL_ARB_color_buffer_float;
public boolean GL_ARB_compatibility;
public boolean GL_ARB_compressed_texture_pixel_storage;
public boolean GL_ARB_compute_shader;
public boolean GL_ARB_compute_variable_group_size;
public boolean GL_ARB_conservative_depth;
public boolean GL_ARB_copy_buffer;
public boolean GL_ARB_copy_image;
public boolean GL_ARB_debug_output;
public boolean GL_ARB_depth_buffer_float;
public boolean GL_ARB_depth_clamp;
public boolean GL_ARB_depth_texture;
public boolean GL_ARB_draw_buffers;
public boolean GL_ARB_draw_buffers_blend;
public boolean GL_ARB_draw_elements_base_vertex;
public boolean GL_ARB_draw_indirect;
public boolean GL_ARB_draw_instanced;
public boolean GL_ARB_enhanced_layouts;
public boolean GL_ARB_explicit_attrib_location;
public boolean GL_ARB_explicit_uniform_location;
public boolean GL_ARB_fragment_coord_conventions;
public boolean GL_ARB_fragment_layer_viewport;
public boolean GL_ARB_fragment_program;
public boolean GL_ARB_fragment_program_shadow;
public boolean GL_ARB_fragment_shader;
public boolean GL_ARB_framebuffer_no_attachments;
public boolean GL_ARB_framebuffer_object;
public boolean GL_ARB_framebuffer_sRGB;
public boolean GL_ARB_geometry_shader4;
public boolean GL_ARB_get_program_binary;
public boolean GL_ARB_gpu_shader5;
public boolean GL_ARB_gpu_shader_fp64;
public boolean GL_ARB_half_float_pixel;
public boolean GL_ARB_half_float_vertex;
public boolean GL_ARB_imaging;
public boolean GL_ARB_indirect_parameters;
public boolean GL_ARB_instanced_arrays;
public boolean GL_ARB_internalformat_query;
public boolean GL_ARB_internalformat_query2;
public boolean GL_ARB_invalidate_subdata;
public boolean GL_ARB_map_buffer_alignment;
public boolean GL_ARB_map_buffer_range;
public boolean GL_ARB_matrix_palette;
public boolean GL_ARB_multi_bind;
public boolean GL_ARB_multi_draw_indirect;
public boolean GL_ARB_multisample;
public boolean GL_ARB_multitexture;
public boolean GL_ARB_occlusion_query;
public boolean GL_ARB_occlusion_query2;
public boolean GL_ARB_pixel_buffer_object;
public boolean GL_ARB_point_parameters;
public boolean GL_ARB_point_sprite;
public boolean GL_ARB_program_interface_query;
public boolean GL_ARB_provoking_vertex;
public boolean GL_ARB_query_buffer_object;
public boolean GL_ARB_robust_buffer_access_behavior;
public boolean GL_ARB_robustness;
public boolean GL_ARB_robustness_isolation;
public boolean GL_ARB_sample_shading;
public boolean GL_ARB_sampler_objects;
public boolean GL_ARB_seamless_cube_map;
public boolean GL_ARB_seamless_cubemap_per_texture;
public boolean GL_ARB_separate_shader_objects;
public boolean GL_ARB_shader_atomic_counters;
public boolean GL_ARB_shader_bit_encoding;
public boolean GL_ARB_shader_draw_parameters;
public boolean GL_ARB_shader_group_vote;
public boolean GL_ARB_shader_image_load_store;
public boolean GL_ARB_shader_image_size;
public boolean GL_ARB_shader_objects;
public boolean GL_ARB_shader_precision;
public boolean GL_ARB_shader_stencil_export;
public boolean GL_ARB_shader_storage_buffer_object;
public boolean GL_ARB_shader_subroutine;
public boolean GL_ARB_shader_texture_lod;
public boolean GL_ARB_shading_language_100;
public boolean GL_ARB_shading_language_420pack;
public boolean GL_ARB_shading_language_include;
public boolean GL_ARB_shading_language_packing;
public boolean GL_ARB_shadow;
public boolean GL_ARB_shadow_ambient;
public boolean GL_ARB_sparse_texture;
public boolean GL_ARB_stencil_texturing;
public boolean GL_ARB_sync;
public boolean GL_ARB_tessellation_shader;
public boolean GL_ARB_texture_border_clamp;
public boolean GL_ARB_texture_buffer_object;
public boolean GL_ARB_texture_buffer_object_rgb32;
public boolean GL_ARB_texture_buffer_range;
public boolean GL_ARB_texture_compression;
public boolean GL_ARB_texture_compression_bptc;
public boolean GL_ARB_texture_compression_rgtc;
public boolean GL_ARB_texture_cube_map;
public boolean GL_ARB_texture_cube_map_array;
public boolean GL_ARB_texture_env_add;
public boolean GL_ARB_texture_env_combine;
public boolean GL_ARB_texture_env_crossbar;
public boolean GL_ARB_texture_env_dot3;
public boolean GL_ARB_texture_float;;
public boolean GL_ARB_texture_gather;
public boolean GL_ARB_texture_mirror_clamp_to_edge;
public boolean GL_ARB_texture_mirrored_repeat;
public boolean GL_ARB_texture_multisample;
public boolean GL_ARB_texture_non_power_of_two;
public boolean GL_ARB_texture_query_levels;
public boolean GL_ARB_texture_query_lod;
public boolean GL_ARB_texture_rectangle;
public boolean GL_ARB_texture_rg;
public boolean GL_ARB_texture_rgb10_a2ui;
public boolean GL_ARB_texture_stencil8;
public boolean GL_ARB_texture_storage;
public boolean GL_ARB_texture_storage_multisample;
public boolean GL_ARB_texture_swizzle;
public boolean GL_ARB_texture_view;
public boolean GL_ARB_timer_query;
public boolean GL_ARB_transform_feedback2;
public boolean GL_ARB_transform_feedback3;
public boolean GL_ARB_transform_feedback_instanced;
public boolean GL_ARB_transpose_matrix;
public boolean GL_ARB_uniform_buffer_object;
public boolean GL_ARB_vertex_array_bgra;
public boolean GL_ARB_vertex_array_object;
public boolean GL_ARB_vertex_attrib_64bit;
public boolean GL_ARB_vertex_attrib_binding;
public boolean GL_ARB_vertex_blend;
public boolean GL_ARB_vertex_buffer_object;
public boolean GL_ARB_vertex_program;
public boolean GL_ARB_vertex_shader;
public boolean GL_ARB_vertex_type_10f_11f_11f_rev;
public boolean GL_ARB_vertex_type_2_10_10_10_rev;
public boolean GL_ARB_viewport_array;
public boolean GL_ARB_window_pos;
public boolean GL_ATI_draw_buffers;
public boolean GL_ATI_element_array;
public boolean GL_ATI_envmap_bumpmap;
public boolean GL_ATI_fragment_shader;
public boolean GL_ATI_map_object_buffer;
public boolean GL_ATI_meminfo;
public boolean GL_ATI_pn_triangles;
public boolean GL_ATI_separate_stencil;
public boolean GL_ATI_shader_texture_lod;
public boolean GL_ATI_text_fragment_shader;
public boolean GL_ATI_texture_compression_3dc;
public boolean GL_ATI_texture_env_combine3;
public boolean GL_ATI_texture_float;
public boolean GL_ATI_texture_mirror_once;
public boolean GL_ATI_vertex_array_object;
public boolean GL_ATI_vertex_attrib_array_object;
public boolean GL_ATI_vertex_streams;
public boolean GL_EXT_abgr;
public boolean GL_EXT_bgra;
public boolean GL_EXT_bindable_uniform;
public boolean GL_EXT_blend_color;
public boolean GL_EXT_blend_equation_separate;
public boolean GL_EXT_blend_func_separate;
public boolean GL_EXT_blend_minmax;
public boolean GL_EXT_blend_subtract;
public boolean GL_EXT_Cg_shader;
public boolean GL_EXT_compiled_vertex_array;
public boolean GL_EXT_depth_bounds_test;
public boolean GL_EXT_direct_state_access;
public boolean GL_EXT_draw_buffers2;
public boolean GL_EXT_draw_instanced;
public boolean GL_EXT_draw_range_elements;
public boolean GL_EXT_fog_coord;
public boolean GL_EXT_framebuffer_blit;
public boolean GL_EXT_framebuffer_multisample;
public boolean GL_EXT_framebuffer_multisample_blit_scaled;
public boolean GL_EXT_framebuffer_object;
public boolean GL_EXT_framebuffer_sRGB;
public boolean GL_EXT_geometry_shader4;
public boolean GL_EXT_gpu_program_parameters;
public boolean GL_EXT_gpu_shader4;
public boolean GL_EXT_multi_draw_arrays;
public boolean GL_EXT_packed_depth_stencil;
public boolean GL_EXT_packed_float;
public boolean GL_EXT_packed_pixels;
public boolean GL_EXT_paletted_texture;
public boolean GL_EXT_pixel_buffer_object;
public boolean GL_EXT_point_parameters;
public boolean GL_EXT_provoking_vertex;
public boolean GL_EXT_rescale_normal;
public boolean GL_EXT_secondary_color;
public boolean GL_EXT_separate_shader_objects;
public boolean GL_EXT_separate_specular_color;
public boolean GL_EXT_shader_image_load_store;
public boolean GL_EXT_shadow_funcs;
public boolean GL_EXT_shared_texture_palette;
public boolean GL_EXT_stencil_clear_tag;
public boolean GL_EXT_stencil_two_side;
public boolean GL_EXT_stencil_wrap;
public boolean GL_EXT_texture_3d;
public boolean GL_EXT_texture_array;
public boolean GL_EXT_texture_buffer_object;
public boolean GL_EXT_texture_compression_latc;
public boolean GL_EXT_texture_compression_rgtc;
public boolean GL_EXT_texture_compression_s3tc;
public boolean GL_EXT_texture_env_combine;
public boolean GL_EXT_texture_env_dot3;
public boolean GL_EXT_texture_filter_anisotropic;
public boolean GL_EXT_texture_integer;
public boolean GL_EXT_texture_lod_bias;
public boolean GL_EXT_texture_mirror_clamp;
public boolean GL_EXT_texture_rectangle;
public boolean GL_EXT_texture_sRGB;
public boolean GL_EXT_texture_sRGB_decode;
public boolean GL_EXT_texture_shared_exponent;
public boolean GL_EXT_texture_snorm;
public boolean GL_EXT_texture_swizzle;
public boolean GL_EXT_timer_query;
public boolean GL_EXT_transform_feedback;
public boolean GL_EXT_vertex_array_bgra;
public boolean GL_EXT_vertex_attrib_64bit;
public boolean GL_EXT_vertex_shader;
public boolean GL_EXT_vertex_weighting;
public boolean OpenGL11;
public boolean OpenGL12;
public boolean OpenGL13;
public boolean OpenGL14;
public boolean OpenGL15;
public boolean OpenGL20;
public boolean OpenGL21;
public boolean OpenGL30;
public boolean OpenGL31;
public boolean OpenGL32;
public boolean OpenGL33;
public boolean OpenGL40;
public boolean OpenGL41;
public boolean OpenGL42;
public boolean OpenGL43;
public boolean OpenGL44;
public boolean GL_GREMEDY_frame_terminator;
public boolean GL_GREMEDY_string_marker;
public boolean GL_HP_occlusion_test;
public boolean GL_IBM_rasterpos_clip;
public boolean GL_INTEL_map_texture;
public boolean GL_KHR_debug;
public boolean GL_KHR_texture_compression_astc_ldr;
public boolean GL_NVX_gpu_memory_info;
public boolean GL_NV_bindless_multi_draw_indirect;
public boolean GL_NV_bindless_texture;
public boolean GL_NV_blend_equation_advanced;
public boolean GL_NV_blend_square;
public boolean GL_NV_compute_program5;
public boolean GL_NV_conditional_render;
public boolean GL_NV_copy_depth_to_color;
public boolean GL_NV_copy_image;
public boolean GL_NV_deep_texture3D;
public boolean GL_NV_depth_buffer_float;
public boolean GL_NV_depth_clamp;
public boolean GL_NV_draw_texture;
public boolean GL_NV_evaluators;
public boolean GL_NV_explicit_multisample;
public boolean GL_NV_fence;
public boolean GL_NV_float_buffer;
public boolean GL_NV_fog_distance;
public boolean GL_NV_fragment_program;
public boolean GL_NV_fragment_program2;
public boolean GL_NV_fragment_program4;
public boolean GL_NV_fragment_program_option;
public boolean GL_NV_framebuffer_multisample_coverage;
public boolean GL_NV_geometry_program4;
public boolean GL_NV_geometry_shader4;
public boolean GL_NV_gpu_program4;
public boolean GL_NV_gpu_program5;
public boolean GL_NV_gpu_program5_mem_extended;
public boolean GL_NV_gpu_shader5;
public boolean GL_NV_half_float;
public boolean GL_NV_light_max_exponent;
public boolean GL_NV_multisample_coverage;
public boolean GL_NV_multisample_filter_hint;
public boolean GL_NV_occlusion_query;
public boolean GL_NV_packed_depth_stencil;
public boolean GL_NV_parameter_buffer_object;
public boolean GL_NV_parameter_buffer_object2;
public boolean GL_NV_path_rendering;
public boolean GL_NV_pixel_data_range;
public boolean GL_NV_point_sprite;
public boolean GL_NV_present_video;
public boolean GL_NV_primitive_restart;
public boolean GL_NV_register_combiners;
public boolean GL_NV_register_combiners2;
public boolean GL_NV_shader_atomic_counters;
public boolean GL_NV_shader_atomic_float;
public boolean GL_NV_shader_buffer_load;
public boolean GL_NV_shader_buffer_store;
public boolean GL_NV_shader_storage_buffer_object;
public boolean GL_NV_tessellation_program5;
public boolean GL_NV_texgen_reflection;
public boolean GL_NV_texture_barrier;
public boolean GL_NV_texture_compression_vtc;
public boolean GL_NV_texture_env_combine4;
public boolean GL_NV_texture_expand_normal;
public boolean GL_NV_texture_multisample;
public boolean GL_NV_texture_rectangle;
public boolean GL_NV_texture_shader;
public boolean GL_NV_texture_shader2;
public boolean GL_NV_texture_shader3;
public boolean GL_NV_transform_feedback;
public boolean GL_NV_transform_feedback2;
public boolean GL_NV_vertex_array_range;
public boolean GL_NV_vertex_array_range2;
public boolean GL_NV_vertex_attrib_integer_64bit;
public boolean GL_NV_vertex_buffer_unified_memory;
public boolean GL_NV_vertex_program;
public boolean GL_NV_vertex_program1_1;
public boolean GL_NV_vertex_program2;
public boolean GL_NV_vertex_program2_option;
public boolean GL_NV_vertex_program3;
public boolean GL_NV_vertex_program4;
public boolean GL_NV_video_capture;
public boolean GL_SGIS_generate_mipmap;
public boolean GL_SGIS_texture_lod;
public boolean GL_SUN_slice_accum;
public static void main(String[] arg) {
System.out.println("START!");
new ContextCapabilities();
}
org.lwjgl.opengl.ContextCapabilities cap =
org.lwjgl.opengl.GLContext.createFromCurrent().getCapabilities();
public ContextCapabilities() {
Field[] fields = org.lwjgl.opengl.ContextCapabilities.class.getFields();
try {
for (Field field : fields) {
String name = field.getName();
if (name.startsWith("GL_") || name.startsWith("OpenGL")) {
boolean value = field.getBoolean(cap);
try {
Field f = this.getClass().getField(name);
f.setBoolean(this, value);
} catch (Exception e) {
}
}
}
} catch (Exception e) {
System.out.println(e);
}
}
public boolean GL_AMD_blend_minmax_factor;
public boolean GL_AMD_conservative_depth;
public boolean GL_AMD_debug_output;
public boolean GL_AMD_depth_clamp_separate;
public boolean GL_AMD_draw_buffers_blend;
public boolean GL_AMD_interleaved_elements;
public boolean GL_AMD_multi_draw_indirect;
public boolean GL_AMD_name_gen_delete;
public boolean GL_AMD_performance_monitor;
public boolean GL_AMD_pinned_memory;
public boolean GL_AMD_query_buffer_object;
public boolean GL_AMD_sample_positions;
public boolean GL_AMD_seamless_cubemap_per_texture;
public boolean GL_AMD_shader_atomic_counter_ops;
public boolean GL_AMD_shader_stencil_export;
public boolean GL_AMD_shader_trinary_minmax;
public boolean GL_AMD_sparse_texture;
public boolean GL_AMD_stencil_operation_extended;
public boolean GL_AMD_texture_texture4;
public boolean GL_AMD_transform_feedback3_lines_triangles;
public boolean GL_AMD_vertex_shader_layer;
public boolean GL_AMD_vertex_shader_tessellator;
public boolean GL_AMD_vertex_shader_viewport_index;
public boolean GL_APPLE_aux_depth_stencil;
public boolean GL_APPLE_client_storage;
public boolean GL_APPLE_element_array;
public boolean GL_APPLE_fence;
public boolean GL_APPLE_float_pixels;
public boolean GL_APPLE_flush_buffer_range;
public boolean GL_APPLE_object_purgeable;
public boolean GL_APPLE_packed_pixels;
public boolean GL_APPLE_rgb_422;
public boolean GL_APPLE_row_bytes;
public boolean GL_APPLE_texture_range;
public boolean GL_APPLE_vertex_array_object;
public boolean GL_APPLE_vertex_array_range;
public boolean GL_APPLE_vertex_program_evaluators;
public boolean GL_APPLE_ycbcr_422;
public boolean GL_ARB_ES2_compatibility;
public boolean GL_ARB_ES3_compatibility;
public boolean GL_ARB_arrays_of_arrays;
public boolean GL_ARB_base_instance;
public boolean GL_ARB_bindless_texture;
public boolean GL_ARB_blend_func_extended;
public boolean GL_ARB_buffer_storage;
public boolean GL_ARB_cl_event;
public boolean GL_ARB_clear_buffer_object;
public boolean GL_ARB_clear_texture;
public boolean GL_ARB_color_buffer_float;
public boolean GL_ARB_compatibility;
public boolean GL_ARB_compressed_texture_pixel_storage;
public boolean GL_ARB_compute_shader;
public boolean GL_ARB_compute_variable_group_size;
public boolean GL_ARB_conservative_depth;
public boolean GL_ARB_copy_buffer;
public boolean GL_ARB_copy_image;
public boolean GL_ARB_debug_output;
public boolean GL_ARB_depth_buffer_float;
public boolean GL_ARB_depth_clamp;
public boolean GL_ARB_depth_texture;
public boolean GL_ARB_draw_buffers;
public boolean GL_ARB_draw_buffers_blend;
public boolean GL_ARB_draw_elements_base_vertex;
public boolean GL_ARB_draw_indirect;
public boolean GL_ARB_draw_instanced;
public boolean GL_ARB_enhanced_layouts;
public boolean GL_ARB_explicit_attrib_location;
public boolean GL_ARB_explicit_uniform_location;
public boolean GL_ARB_fragment_coord_conventions;
public boolean GL_ARB_fragment_layer_viewport;
public boolean GL_ARB_fragment_program;
public boolean GL_ARB_fragment_program_shadow;
public boolean GL_ARB_fragment_shader;
public boolean GL_ARB_framebuffer_no_attachments;
public boolean GL_ARB_framebuffer_object;
public boolean GL_ARB_framebuffer_sRGB;
public boolean GL_ARB_geometry_shader4;
public boolean GL_ARB_get_program_binary;
public boolean GL_ARB_gpu_shader5;
public boolean GL_ARB_gpu_shader_fp64;
public boolean GL_ARB_half_float_pixel;
public boolean GL_ARB_half_float_vertex;
public boolean GL_ARB_imaging;
public boolean GL_ARB_indirect_parameters;
public boolean GL_ARB_instanced_arrays;
public boolean GL_ARB_internalformat_query;
public boolean GL_ARB_internalformat_query2;
public boolean GL_ARB_invalidate_subdata;
public boolean GL_ARB_map_buffer_alignment;
public boolean GL_ARB_map_buffer_range;
public boolean GL_ARB_matrix_palette;
public boolean GL_ARB_multi_bind;
public boolean GL_ARB_multi_draw_indirect;
public boolean GL_ARB_multisample;
public boolean GL_ARB_multitexture;
public boolean GL_ARB_occlusion_query;
public boolean GL_ARB_occlusion_query2;
public boolean GL_ARB_pixel_buffer_object;
public boolean GL_ARB_point_parameters;
public boolean GL_ARB_point_sprite;
public boolean GL_ARB_program_interface_query;
public boolean GL_ARB_provoking_vertex;
public boolean GL_ARB_query_buffer_object;
public boolean GL_ARB_robust_buffer_access_behavior;
public boolean GL_ARB_robustness;
public boolean GL_ARB_robustness_isolation;
public boolean GL_ARB_sample_shading;
public boolean GL_ARB_sampler_objects;
public boolean GL_ARB_seamless_cube_map;
public boolean GL_ARB_seamless_cubemap_per_texture;
public boolean GL_ARB_separate_shader_objects;
public boolean GL_ARB_shader_atomic_counters;
public boolean GL_ARB_shader_bit_encoding;
public boolean GL_ARB_shader_draw_parameters;
public boolean GL_ARB_shader_group_vote;
public boolean GL_ARB_shader_image_load_store;
public boolean GL_ARB_shader_image_size;
public boolean GL_ARB_shader_objects;
public boolean GL_ARB_shader_precision;
public boolean GL_ARB_shader_stencil_export;
public boolean GL_ARB_shader_storage_buffer_object;
public boolean GL_ARB_shader_subroutine;
public boolean GL_ARB_shader_texture_lod;
public boolean GL_ARB_shading_language_100;
public boolean GL_ARB_shading_language_420pack;
public boolean GL_ARB_shading_language_include;
public boolean GL_ARB_shading_language_packing;
public boolean GL_ARB_shadow;
public boolean GL_ARB_shadow_ambient;
public boolean GL_ARB_sparse_texture;
public boolean GL_ARB_stencil_texturing;
public boolean GL_ARB_sync;
public boolean GL_ARB_tessellation_shader;
public boolean GL_ARB_texture_border_clamp;
public boolean GL_ARB_texture_buffer_object;
public boolean GL_ARB_texture_buffer_object_rgb32;
public boolean GL_ARB_texture_buffer_range;
public boolean GL_ARB_texture_compression;
public boolean GL_ARB_texture_compression_bptc;
public boolean GL_ARB_texture_compression_rgtc;
public boolean GL_ARB_texture_cube_map;
public boolean GL_ARB_texture_cube_map_array;
public boolean GL_ARB_texture_env_add;
public boolean GL_ARB_texture_env_combine;
public boolean GL_ARB_texture_env_crossbar;
public boolean GL_ARB_texture_env_dot3;
public boolean GL_ARB_texture_float;
;
public boolean GL_ARB_texture_gather;
public boolean GL_ARB_texture_mirror_clamp_to_edge;
public boolean GL_ARB_texture_mirrored_repeat;
public boolean GL_ARB_texture_multisample;
public boolean GL_ARB_texture_non_power_of_two;
public boolean GL_ARB_texture_query_levels;
public boolean GL_ARB_texture_query_lod;
public boolean GL_ARB_texture_rectangle;
public boolean GL_ARB_texture_rg;
public boolean GL_ARB_texture_rgb10_a2ui;
public boolean GL_ARB_texture_stencil8;
public boolean GL_ARB_texture_storage;
public boolean GL_ARB_texture_storage_multisample;
public boolean GL_ARB_texture_swizzle;
public boolean GL_ARB_texture_view;
public boolean GL_ARB_timer_query;
public boolean GL_ARB_transform_feedback2;
public boolean GL_ARB_transform_feedback3;
public boolean GL_ARB_transform_feedback_instanced;
public boolean GL_ARB_transpose_matrix;
public boolean GL_ARB_uniform_buffer_object;
public boolean GL_ARB_vertex_array_bgra;
public boolean GL_ARB_vertex_array_object;
public boolean GL_ARB_vertex_attrib_64bit;
public boolean GL_ARB_vertex_attrib_binding;
public boolean GL_ARB_vertex_blend;
public boolean GL_ARB_vertex_buffer_object;
public boolean GL_ARB_vertex_program;
public boolean GL_ARB_vertex_shader;
public boolean GL_ARB_vertex_type_10f_11f_11f_rev;
public boolean GL_ARB_vertex_type_2_10_10_10_rev;
public boolean GL_ARB_viewport_array;
public boolean GL_ARB_window_pos;
public boolean GL_ATI_draw_buffers;
public boolean GL_ATI_element_array;
public boolean GL_ATI_envmap_bumpmap;
public boolean GL_ATI_fragment_shader;
public boolean GL_ATI_map_object_buffer;
public boolean GL_ATI_meminfo;
public boolean GL_ATI_pn_triangles;
public boolean GL_ATI_separate_stencil;
public boolean GL_ATI_shader_texture_lod;
public boolean GL_ATI_text_fragment_shader;
public boolean GL_ATI_texture_compression_3dc;
public boolean GL_ATI_texture_env_combine3;
public boolean GL_ATI_texture_float;
public boolean GL_ATI_texture_mirror_once;
public boolean GL_ATI_vertex_array_object;
public boolean GL_ATI_vertex_attrib_array_object;
public boolean GL_ATI_vertex_streams;
public boolean GL_EXT_abgr;
public boolean GL_EXT_bgra;
public boolean GL_EXT_bindable_uniform;
public boolean GL_EXT_blend_color;
public boolean GL_EXT_blend_equation_separate;
public boolean GL_EXT_blend_func_separate;
public boolean GL_EXT_blend_minmax;
public boolean GL_EXT_blend_subtract;
public boolean GL_EXT_Cg_shader;
public boolean GL_EXT_compiled_vertex_array;
public boolean GL_EXT_depth_bounds_test;
public boolean GL_EXT_direct_state_access;
public boolean GL_EXT_draw_buffers2;
public boolean GL_EXT_draw_instanced;
public boolean GL_EXT_draw_range_elements;
public boolean GL_EXT_fog_coord;
public boolean GL_EXT_framebuffer_blit;
public boolean GL_EXT_framebuffer_multisample;
public boolean GL_EXT_framebuffer_multisample_blit_scaled;
public boolean GL_EXT_framebuffer_object;
public boolean GL_EXT_framebuffer_sRGB;
public boolean GL_EXT_geometry_shader4;
public boolean GL_EXT_gpu_program_parameters;
public boolean GL_EXT_gpu_shader4;
public boolean GL_EXT_multi_draw_arrays;
public boolean GL_EXT_packed_depth_stencil;
public boolean GL_EXT_packed_float;
public boolean GL_EXT_packed_pixels;
public boolean GL_EXT_paletted_texture;
public boolean GL_EXT_pixel_buffer_object;
public boolean GL_EXT_point_parameters;
public boolean GL_EXT_provoking_vertex;
public boolean GL_EXT_rescale_normal;
public boolean GL_EXT_secondary_color;
public boolean GL_EXT_separate_shader_objects;
public boolean GL_EXT_separate_specular_color;
public boolean GL_EXT_shader_image_load_store;
public boolean GL_EXT_shadow_funcs;
public boolean GL_EXT_shared_texture_palette;
public boolean GL_EXT_stencil_clear_tag;
public boolean GL_EXT_stencil_two_side;
public boolean GL_EXT_stencil_wrap;
public boolean GL_EXT_texture_3d;
public boolean GL_EXT_texture_array;
public boolean GL_EXT_texture_buffer_object;
public boolean GL_EXT_texture_compression_latc;
public boolean GL_EXT_texture_compression_rgtc;
public boolean GL_EXT_texture_compression_s3tc;
public boolean GL_EXT_texture_env_combine;
public boolean GL_EXT_texture_env_dot3;
public boolean GL_EXT_texture_filter_anisotropic;
public boolean GL_EXT_texture_integer;
public boolean GL_EXT_texture_lod_bias;
public boolean GL_EXT_texture_mirror_clamp;
public boolean GL_EXT_texture_rectangle;
public boolean GL_EXT_texture_sRGB;
public boolean GL_EXT_texture_sRGB_decode;
public boolean GL_EXT_texture_shared_exponent;
public boolean GL_EXT_texture_snorm;
public boolean GL_EXT_texture_swizzle;
public boolean GL_EXT_timer_query;
public boolean GL_EXT_transform_feedback;
public boolean GL_EXT_vertex_array_bgra;
public boolean GL_EXT_vertex_attrib_64bit;
public boolean GL_EXT_vertex_shader;
public boolean GL_EXT_vertex_weighting;
public boolean OpenGL11;
public boolean OpenGL12;
public boolean OpenGL13;
public boolean OpenGL14;
public boolean OpenGL15;
public boolean OpenGL20;
public boolean OpenGL21;
public boolean OpenGL30;
public boolean OpenGL31;
public boolean OpenGL32;
public boolean OpenGL33;
public boolean OpenGL40;
public boolean OpenGL41;
public boolean OpenGL42;
public boolean OpenGL43;
public boolean OpenGL44;
public boolean GL_GREMEDY_frame_terminator;
public boolean GL_GREMEDY_string_marker;
public boolean GL_HP_occlusion_test;
public boolean GL_IBM_rasterpos_clip;
public boolean GL_INTEL_map_texture;
public boolean GL_KHR_debug;
public boolean GL_KHR_texture_compression_astc_ldr;
public boolean GL_NVX_gpu_memory_info;
public boolean GL_NV_bindless_multi_draw_indirect;
public boolean GL_NV_bindless_texture;
public boolean GL_NV_blend_equation_advanced;
public boolean GL_NV_blend_square;
public boolean GL_NV_compute_program5;
public boolean GL_NV_conditional_render;
public boolean GL_NV_copy_depth_to_color;
public boolean GL_NV_copy_image;
public boolean GL_NV_deep_texture3D;
public boolean GL_NV_depth_buffer_float;
public boolean GL_NV_depth_clamp;
public boolean GL_NV_draw_texture;
public boolean GL_NV_evaluators;
public boolean GL_NV_explicit_multisample;
public boolean GL_NV_fence;
public boolean GL_NV_float_buffer;
public boolean GL_NV_fog_distance;
public boolean GL_NV_fragment_program;
public boolean GL_NV_fragment_program2;
public boolean GL_NV_fragment_program4;
public boolean GL_NV_fragment_program_option;
public boolean GL_NV_framebuffer_multisample_coverage;
public boolean GL_NV_geometry_program4;
public boolean GL_NV_geometry_shader4;
public boolean GL_NV_gpu_program4;
public boolean GL_NV_gpu_program5;
public boolean GL_NV_gpu_program5_mem_extended;
public boolean GL_NV_gpu_shader5;
public boolean GL_NV_half_float;
public boolean GL_NV_light_max_exponent;
public boolean GL_NV_multisample_coverage;
public boolean GL_NV_multisample_filter_hint;
public boolean GL_NV_occlusion_query;
public boolean GL_NV_packed_depth_stencil;
public boolean GL_NV_parameter_buffer_object;
public boolean GL_NV_parameter_buffer_object2;
public boolean GL_NV_path_rendering;
public boolean GL_NV_pixel_data_range;
public boolean GL_NV_point_sprite;
public boolean GL_NV_present_video;
public boolean GL_NV_primitive_restart;
public boolean GL_NV_register_combiners;
public boolean GL_NV_register_combiners2;
public boolean GL_NV_shader_atomic_counters;
public boolean GL_NV_shader_atomic_float;
public boolean GL_NV_shader_buffer_load;
public boolean GL_NV_shader_buffer_store;
public boolean GL_NV_shader_storage_buffer_object;
public boolean GL_NV_tessellation_program5;
public boolean GL_NV_texgen_reflection;
public boolean GL_NV_texture_barrier;
public boolean GL_NV_texture_compression_vtc;
public boolean GL_NV_texture_env_combine4;
public boolean GL_NV_texture_expand_normal;
public boolean GL_NV_texture_multisample;
public boolean GL_NV_texture_rectangle;
public boolean GL_NV_texture_shader;
public boolean GL_NV_texture_shader2;
public boolean GL_NV_texture_shader3;
public boolean GL_NV_transform_feedback;
public boolean GL_NV_transform_feedback2;
public boolean GL_NV_vertex_array_range;
public boolean GL_NV_vertex_array_range2;
public boolean GL_NV_vertex_attrib_integer_64bit;
public boolean GL_NV_vertex_buffer_unified_memory;
public boolean GL_NV_vertex_program;
public boolean GL_NV_vertex_program1_1;
public boolean GL_NV_vertex_program2;
public boolean GL_NV_vertex_program2_option;
public boolean GL_NV_vertex_program3;
public boolean GL_NV_vertex_program4;
public boolean GL_NV_video_capture;
public boolean GL_SGIS_generate_mipmap;
public boolean GL_SGIS_texture_lod;
public boolean GL_SUN_slice_accum;
public static void main(String[] arg) {
System.out.println("START!");
new ContextCapabilities();
}
}
+13 -32
View File
@@ -47,44 +47,25 @@ import org.lwjglx.PointerBuffer;
*/
final class ContextGL implements Context {
public void releaseCurrent() throws LWJGLException {
}
public void releaseCurrent() throws LWJGLException {}
public synchronized void releaseDrawable() throws LWJGLException {
}
public synchronized void releaseDrawable() throws LWJGLException {}
public synchronized void update() {
}
public synchronized void update() {}
public static void swapBuffers() throws LWJGLException {
}
public static void swapBuffers() throws LWJGLException {}
public synchronized void makeCurrent() throws LWJGLException {
}
public synchronized void makeCurrent() throws LWJGLException {}
public synchronized boolean isCurrent() throws LWJGLException {
return false;
}
public synchronized boolean isCurrent() throws LWJGLException {
return false;
}
public static void setSwapInterval(int value) {
}
public static void setSwapInterval(int value) {}
public synchronized void forceDestroy() throws LWJGLException {
}
public synchronized void forceDestroy() throws LWJGLException {}
public synchronized void destroy() throws LWJGLException {
}
public synchronized void destroy() throws LWJGLException {}
public synchronized void setCLSharingProperties(final PointerBuffer properties) throws LWJGLException {
}
}
public synchronized void setCLSharingProperties(final PointerBuffer properties) throws LWJGLException {}
}
+443 -453
View File
@@ -1,8 +1,6 @@
package org.lwjglx.opengl;
import static org.lwjgl.opengl.GL11.GL_FALSE;
import static org.lwjgl.opengl.GL11.GL_TRUE;
import static org.lwjgl.system.MemoryUtil.NULL;
import static org.lwjgl.glfw.Callbacks.*;
import static org.lwjgl.glfw.GLFW.GLFW_OPENGL_DEBUG_CONTEXT;
import static org.lwjgl.glfw.GLFW.GLFW_RELEASE;
import static org.lwjgl.glfw.GLFW.GLFW_RESIZABLE;
@@ -20,483 +18,475 @@ import static org.lwjgl.glfw.GLFW.glfwSwapBuffers;
import static org.lwjgl.glfw.GLFW.glfwSwapInterval;
import static org.lwjgl.glfw.GLFW.glfwWindowHint;
import static org.lwjgl.glfw.GLFW.glfwWindowShouldClose;
import static org.lwjgl.glfw.Callbacks.*;
import static org.lwjgl.opengl.GL11.GL_FALSE;
import static org.lwjgl.opengl.GL11.GL_TRUE;
import static org.lwjgl.system.MemoryUtil.NULL;
import java.nio.ByteBuffer;
import java.nio.IntBuffer;
import org.lwjgl.BufferUtils;
import org.lwjgl.opengl.GL11;
import org.lwjgl.glfw.*;
import org.lwjgl.glfw.GLFW;
import org.lwjgl.glfw.GLFWCharCallback;
import org.lwjgl.glfw.GLFWCursorPosCallback;
import org.lwjgl.glfw.GLFWKeyCallback;
import org.lwjgl.glfw.GLFWMouseButtonCallback;
import org.lwjgl.glfw.GLFWvidmode;
import org.lwjgl.glfw.GLFWWindowFocusCallback;
import org.lwjgl.glfw.GLFWWindowIconifyCallback;
import org.lwjgl.glfw.GLFWWindowPosCallback;
import org.lwjgl.glfw.GLFWWindowRefreshCallback;
import org.lwjgl.glfw.*;
import org.lwjgl.glfw.GLFWvidmode;
import org.lwjgl.opengl.GL11;
import org.lwjglx.LWJGLException;
import org.lwjglx.Sys;
import org.lwjglx.input.Keyboard;
import org.lwjglx.input.Mouse;
public class Display {
private static String windowTitle = "Game";
private static org.lwjgl.opengl.GLContext context;
private static boolean displayCreated = false;
private static boolean displayFocused = false;
private static boolean displayVisible = true;
private static boolean displayDirty = false;
private static boolean displayResizable = false;
private static DisplayMode mode = new DisplayMode(640, 480);
private static DisplayMode desktopDisplayMode = new DisplayMode(640, 480);
private static int latestEventKey = 0;
private static int displayX = 0;
private static int displayY = 0;
private static boolean displayResized = false;
private static int displayWidth = 0;
private static int displayHeight = 0;
private static int displayFramebufferWidth = 0;
private static int displayFramebufferHeight = 0;
private static boolean latestResized = false;
private static int latestWidth = 0;
private static int latestHeight = 0;
static {
Sys.initialize(); // init using dummy sys method
long monitor = glfwGetPrimaryMonitor();
ByteBuffer vidmode = glfwGetVideoMode(monitor);
int monitorWidth = GLFWvidmode.width(vidmode);
int monitorHeight = GLFWvidmode.height(vidmode);
int monitorBitPerPixel = GLFWvidmode.redBits(vidmode) + GLFWvidmode.greenBits(vidmode) + GLFWvidmode.blueBits(vidmode);
int monitorRefreshRate = GLFWvidmode.refreshRate(vidmode);
desktopDisplayMode = new DisplayMode(monitorWidth, monitorHeight, monitorBitPerPixel, monitorRefreshRate);
}
public static void create(PixelFormat pixel_format, Drawable shared_drawable) throws LWJGLException {
System.out.println("TODO: Implement Display.create(PixelFormat, Drawable)"); // TODO
create();
}
public static void create(PixelFormat pixel_format, ContextAttribs attribs) throws LWJGLException {
System.out.println("TODO: Implement Display.create(PixelFormat, ContextAttribs)"); // TODO
create();
}
public static void create(PixelFormat pixel_format) throws LWJGLException {
System.out.println("TODO: Implement Display.create(PixelFormat)"); // TODO
create();
}
public static void create() throws LWJGLException {
long monitor = glfwGetPrimaryMonitor();
ByteBuffer vidmode = glfwGetVideoMode(monitor);
int monitorWidth = GLFWvidmode.width(vidmode);
int monitorHeight = GLFWvidmode.height(vidmode);
int monitorBitPerPixel = GLFWvidmode.redBits(vidmode) + GLFWvidmode.greenBits(vidmode) + GLFWvidmode.blueBits(vidmode);
int monitorRefreshRate = GLFWvidmode.refreshRate(vidmode);
desktopDisplayMode = new DisplayMode(monitorWidth, monitorHeight, monitorBitPerPixel, monitorRefreshRate);
private static String windowTitle = "Game";
glfwDefaultWindowHints();
glfwWindowHint(GLFW_VISIBLE, GL_FALSE);
glfwWindowHint(GLFW_RESIZABLE, displayResizable ? GL_TRUE : GL_FALSE);
glfwWindowHint(GLFW_OPENGL_DEBUG_CONTEXT, GL_TRUE);
private static org.lwjgl.opengl.GLContext context;
Window.handle = glfwCreateWindow(mode.getWidth(), mode.getHeight(), windowTitle, NULL, NULL);
if ( Window.handle == 0L )
throw new IllegalStateException("Failed to create Display window");
Window.keyCallback = new GLFWKeyCallback() {
@Override
public void invoke(long window, int key, int scancode, int action, int mods) {
latestEventKey = key;
if (action == GLFW_RELEASE || action == GLFW.GLFW_PRESS) {
Keyboard.addKeyEvent(key, action == GLFW.GLFW_PRESS ? true : false);
}
}
};
Window.charCallback = new GLFWCharCallback() {
@Override
public void invoke(long window, int codepoint) {
Keyboard.addCharEvent(latestEventKey, (char)codepoint);
}
};
Window.cursorPosCallback = new GLFWCursorPosCallback() {
@Override
public void invoke(long window, double xpos, double ypos) {
Mouse.addMoveEvent(xpos, ypos);
}
};
Window.mouseButtonCallback = new GLFWMouseButtonCallback() {
@Override
public void invoke(long window, int button, int action, int mods) {
Mouse.addButtonEvent(button, action == GLFW.GLFW_PRESS ? true : false);
}
};
Window.windowFocusCallback = new GLFWWindowFocusCallback() {
@Override
public void invoke(long window, int focused) {
displayFocused = focused == GL11.GL_TRUE;
}
};
Window.windowIconifyCallback = new GLFWWindowIconifyCallback() {
@Override
public void invoke(long window, int iconified) {
displayVisible = iconified == GL11.GL_FALSE;
}
};
Window.windowSizeCallback = new GLFWWindowSizeCallback() {
@Override
public void invoke(long window, int width, int height) {
latestResized = true;
latestWidth = width;
latestHeight = height;
}
};
Window.windowPosCallback = new GLFWWindowPosCallback() {
@Override
public void invoke(long window, int xpos, int ypos) {
displayX = xpos;
displayY = ypos;
}
};
Window.windowRefreshCallback = new GLFWWindowRefreshCallback() {
@Override
public void invoke(long window) {
displayDirty = true;
}
};
Window.framebufferSizeCallback = new GLFWFramebufferSizeCallback() {
@Override
public void invoke(long window, int width, int height) {
displayFramebufferWidth = width;
displayFramebufferHeight = height;
}
};
Window.setCallbacks();
displayWidth = mode.getWidth();
displayHeight = mode.getHeight();
IntBuffer fbw = BufferUtils.createIntBuffer(1);
IntBuffer fbh = BufferUtils.createIntBuffer(1);
GLFW.glfwGetFramebufferSize(Window.handle, fbw, fbh);
displayFramebufferWidth = fbw.get(0);
displayFramebufferHeight = fbh.get(0);
glfwSetWindowPos(
Window.handle,
(monitorWidth - mode.getWidth()) / 2,
(monitorHeight - mode.getHeight()) / 2
);
displayX = (monitorWidth - mode.getWidth()) / 2;
displayY = (monitorHeight - mode.getHeight()) / 2;
private static boolean displayCreated = false;
private static boolean displayFocused = false;
private static boolean displayVisible = true;
private static boolean displayDirty = false;
private static boolean displayResizable = false;
glfwMakeContextCurrent(Window.handle);
context = org.lwjgl.opengl.GLContext.createFromCurrent();
glfwSwapInterval(1);
glfwShowWindow(Window.handle);
displayCreated = true;
}
public static boolean isCreated() {
return displayCreated;
}
public static boolean isActive() {
return displayFocused;
}
public static boolean isVisible() {
return displayVisible;
}
public static org.lwjgl.opengl.GLContext getContext() {
return context;
}
public static void setLocation(int new_x, int new_y) {
System.out.println("TODO: Implement Display.setLocation(int, int)");
}
public static void setVSyncEnabled(boolean sync) {
System.out.println("TODO: Implement Display.setVSyncEnabled(boolean)");// TODO
}
public static long getWindow() {
return Window.handle;
}
public static void update() {
update(true);
}
public static void update(boolean processMessages) {
try {
swapBuffers();
displayDirty = false;
}
catch (LWJGLException e) {
throw new RuntimeException(e);
}
if (processMessages) processMessages();
}
public static void processMessages() {
glfwPollEvents();
Keyboard.poll();
Mouse.poll();
if (latestResized) {
latestResized = false;
displayResized = true;
displayWidth = latestWidth;
displayHeight = latestHeight;
}
else {
displayResized = false;
}
}
public static void swapBuffers() throws LWJGLException {
glfwSwapBuffers(Window.handle);
}
public static void destroy() {
Window.releaseCallbacks();
glfwDestroyWindow(Window.handle);
/*try {
glfwTerminate();
} catch (Throwable t) {
t.printStackTrace();
}*/
displayCreated = false;
}
public static void setDisplayMode(DisplayMode dm) throws LWJGLException {
mode = dm;
}
public static DisplayMode getDisplayMode() {
return mode;
}
public static DisplayMode[] getAvailableDisplayModes() throws LWJGLException {
IntBuffer count = BufferUtils.createIntBuffer(1);
ByteBuffer modes = GLFW.glfwGetVideoModes(GLFW.glfwGetPrimaryMonitor(), count);
private static DisplayMode mode = new DisplayMode(640, 480);
private static DisplayMode desktopDisplayMode = new DisplayMode(640, 480);
DisplayMode[] displayModes = new DisplayMode[count.get(0)];
private static int latestEventKey = 0;
for (int i = 0; i < count.get(0); i++) {
modes.position(i * GLFWvidmode.SIZEOF);
private static int displayX = 0;
private static int displayY = 0;
int w = GLFWvidmode.width(modes);
int h = GLFWvidmode.height(modes);
int b = GLFWvidmode.redBits(modes) + GLFWvidmode.greenBits(modes)
+ GLFWvidmode.blueBits(modes);
int r = GLFWvidmode.refreshRate(modes);
private static boolean displayResized = false;
private static int displayWidth = 0;
private static int displayHeight = 0;
private static int displayFramebufferWidth = 0;
private static int displayFramebufferHeight = 0;
displayModes[i] = new DisplayMode(w, h, b, r);
}
private static boolean latestResized = false;
private static int latestWidth = 0;
private static int latestHeight = 0;
return displayModes;
}
public static DisplayMode getDesktopDisplayMode() {
return desktopDisplayMode;
}
public static boolean wasResized() {
return displayResized;
}
public static int getX() {
return displayX;
}
public static int getY() {
return displayY;
}
public static int getWidth() {
return displayWidth;
}
public static int getHeight() {
return displayHeight;
}
public static int getFramebufferWidth() {
return displayFramebufferWidth;
}
public static int getFramebufferHeight() {
return displayFramebufferHeight;
}
public static void setTitle(String title) {
windowTitle = title;
}
public static boolean isCloseRequested() {
return glfwWindowShouldClose(Window.handle) == GL_TRUE;
}
public static boolean isDirty() {
return displayDirty;
}
public static void setInitialBackground(float red, float green, float blue) {
// TODO
System.out.println("TODO: Implement Display.setInitialBackground(float, float, float)");
}
public static int setIcon(java.nio.ByteBuffer[] icons) {
// TODO
System.out.println("TODO: Implement Display.setIcon(ByteBuffer[])");
return 0;
}
public static void setResizable(boolean resizable) {
displayResizable = resizable;
// TODO
}
public static boolean isResizable() {
return displayResizable;
}
public static void setDisplayModeAndFullscreen(DisplayMode mode) throws LWJGLException {
// TODO
System.out.println("TODO: Implement Display.setDisplayModeAndFullscreen(DisplayMode)");
}
public static void setFullscreen(boolean fullscreen) throws LWJGLException {
// TODO
}
public static boolean isFullscreen() {
// TODO
return false;
}
public static void setParent(java.awt.Canvas parent) throws LWJGLException {
// Do nothing as set parent not supported
}
public static void releaseContext() throws LWJGLException {
glfwMakeContextCurrent(0);
}
public static boolean isCurrent() throws LWJGLException {
return context.isCurrent();
}
public static void makeCurrent() throws LWJGLException {
glfwMakeContextCurrent(Window.handle);
}
public static java.lang.String getAdapter() {
// TODO
return "GeNotSupportedAdapter";
}
public static java.lang.String getVersion() {
// TODO
return "1.0 NOT SUPPORTED";
}
/**
* An accurate sync method that will attempt to run at a constant frame rate.
* It should be called once every frame.
*
* @param fps - the desired frame rate, in frames per second
*/
public static void sync(int fps) {
Sync.sync(fps);
}
public static Drawable getDrawable() {
return null;
}
static DisplayImplementation getImplementation() {
return null;
}
private static class Window {
static long handle;
static GLFWKeyCallback keyCallback;
static GLFWCharCallback charCallback;
static GLFWCursorPosCallback cursorPosCallback;
static GLFWMouseButtonCallback mouseButtonCallback;
static GLFWWindowFocusCallback windowFocusCallback;
static GLFWWindowIconifyCallback windowIconifyCallback;
static GLFWWindowSizeCallback windowSizeCallback;
static GLFWWindowPosCallback windowPosCallback;
static GLFWWindowRefreshCallback windowRefreshCallback;
static GLFWFramebufferSizeCallback framebufferSizeCallback;
public static void setCallbacks() {
glfwSetCallback(handle, keyCallback);
glfwSetCallback(handle, charCallback);
glfwSetCallback(handle, cursorPosCallback);
glfwSetCallback(handle, mouseButtonCallback);
glfwSetCallback(handle, windowFocusCallback);
glfwSetCallback(handle, windowIconifyCallback);
glfwSetCallback(handle, windowSizeCallback);
glfwSetCallback(handle, windowPosCallback);
glfwSetCallback(handle, windowRefreshCallback);
glfwSetCallback(handle, framebufferSizeCallback);
}
public static void releaseCallbacks() {
keyCallback.release();
charCallback.release();
cursorPosCallback.release();
mouseButtonCallback.release();
windowFocusCallback.release();
windowIconifyCallback.release();
windowSizeCallback.release();
windowPosCallback.release();
windowRefreshCallback.release();
framebufferSizeCallback.release();
}
}
static {
Sys.initialize(); // init using dummy sys method
long monitor = glfwGetPrimaryMonitor();
ByteBuffer vidmode = glfwGetVideoMode(monitor);
int monitorWidth = GLFWvidmode.width(vidmode);
int monitorHeight = GLFWvidmode.height(vidmode);
int monitorBitPerPixel =
GLFWvidmode.redBits(vidmode) + GLFWvidmode.greenBits(vidmode) + GLFWvidmode.blueBits(vidmode);
int monitorRefreshRate = GLFWvidmode.refreshRate(vidmode);
desktopDisplayMode = new DisplayMode(monitorWidth, monitorHeight, monitorBitPerPixel, monitorRefreshRate);
}
public static void create(PixelFormat pixel_format, Drawable shared_drawable) throws LWJGLException {
System.out.println("TODO: Implement Display.create(PixelFormat, Drawable)"); // TODO
create();
}
public static void create(PixelFormat pixel_format, ContextAttribs attribs) throws LWJGLException {
System.out.println("TODO: Implement Display.create(PixelFormat, ContextAttribs)"); // TODO
create();
}
public static void create(PixelFormat pixel_format) throws LWJGLException {
System.out.println("TODO: Implement Display.create(PixelFormat)"); // TODO
create();
}
public static void create() throws LWJGLException {
long monitor = glfwGetPrimaryMonitor();
ByteBuffer vidmode = glfwGetVideoMode(monitor);
int monitorWidth = GLFWvidmode.width(vidmode);
int monitorHeight = GLFWvidmode.height(vidmode);
int monitorBitPerPixel =
GLFWvidmode.redBits(vidmode) + GLFWvidmode.greenBits(vidmode) + GLFWvidmode.blueBits(vidmode);
int monitorRefreshRate = GLFWvidmode.refreshRate(vidmode);
desktopDisplayMode = new DisplayMode(monitorWidth, monitorHeight, monitorBitPerPixel, monitorRefreshRate);
glfwDefaultWindowHints();
glfwWindowHint(GLFW_VISIBLE, GL_FALSE);
glfwWindowHint(GLFW_RESIZABLE, displayResizable ? GL_TRUE : GL_FALSE);
glfwWindowHint(GLFW_OPENGL_DEBUG_CONTEXT, GL_TRUE);
Window.handle = glfwCreateWindow(mode.getWidth(), mode.getHeight(), windowTitle, NULL, NULL);
if (Window.handle == 0L) throw new IllegalStateException("Failed to create Display window");
Window.keyCallback = new GLFWKeyCallback() {
@Override
public void invoke(long window, int key, int scancode, int action, int mods) {
latestEventKey = key;
if (action == GLFW_RELEASE || action == GLFW.GLFW_PRESS) {
Keyboard.addKeyEvent(key, action == GLFW.GLFW_PRESS ? true : false);
}
}
};
Window.charCallback = new GLFWCharCallback() {
@Override
public void invoke(long window, int codepoint) {
Keyboard.addCharEvent(latestEventKey, (char) codepoint);
}
};
Window.cursorPosCallback = new GLFWCursorPosCallback() {
@Override
public void invoke(long window, double xpos, double ypos) {
Mouse.addMoveEvent(xpos, ypos);
}
};
Window.mouseButtonCallback = new GLFWMouseButtonCallback() {
@Override
public void invoke(long window, int button, int action, int mods) {
Mouse.addButtonEvent(button, action == GLFW.GLFW_PRESS ? true : false);
}
};
Window.windowFocusCallback = new GLFWWindowFocusCallback() {
@Override
public void invoke(long window, int focused) {
displayFocused = focused == GL11.GL_TRUE;
}
};
Window.windowIconifyCallback = new GLFWWindowIconifyCallback() {
@Override
public void invoke(long window, int iconified) {
displayVisible = iconified == GL11.GL_FALSE;
}
};
Window.windowSizeCallback = new GLFWWindowSizeCallback() {
@Override
public void invoke(long window, int width, int height) {
latestResized = true;
latestWidth = width;
latestHeight = height;
}
};
Window.windowPosCallback = new GLFWWindowPosCallback() {
@Override
public void invoke(long window, int xpos, int ypos) {
displayX = xpos;
displayY = ypos;
}
};
Window.windowRefreshCallback = new GLFWWindowRefreshCallback() {
@Override
public void invoke(long window) {
displayDirty = true;
}
};
Window.framebufferSizeCallback = new GLFWFramebufferSizeCallback() {
@Override
public void invoke(long window, int width, int height) {
displayFramebufferWidth = width;
displayFramebufferHeight = height;
}
};
Window.setCallbacks();
displayWidth = mode.getWidth();
displayHeight = mode.getHeight();
IntBuffer fbw = BufferUtils.createIntBuffer(1);
IntBuffer fbh = BufferUtils.createIntBuffer(1);
GLFW.glfwGetFramebufferSize(Window.handle, fbw, fbh);
displayFramebufferWidth = fbw.get(0);
displayFramebufferHeight = fbh.get(0);
glfwSetWindowPos(Window.handle, (monitorWidth - mode.getWidth()) / 2, (monitorHeight - mode.getHeight()) / 2);
displayX = (monitorWidth - mode.getWidth()) / 2;
displayY = (monitorHeight - mode.getHeight()) / 2;
glfwMakeContextCurrent(Window.handle);
context = org.lwjgl.opengl.GLContext.createFromCurrent();
glfwSwapInterval(1);
glfwShowWindow(Window.handle);
displayCreated = true;
}
public static boolean isCreated() {
return displayCreated;
}
public static boolean isActive() {
return displayFocused;
}
public static boolean isVisible() {
return displayVisible;
}
public static org.lwjgl.opengl.GLContext getContext() {
return context;
}
public static void setLocation(int new_x, int new_y) {
System.out.println("TODO: Implement Display.setLocation(int, int)");
}
public static void setVSyncEnabled(boolean sync) {
System.out.println("TODO: Implement Display.setVSyncEnabled(boolean)"); // TODO
}
public static long getWindow() {
return Window.handle;
}
public static void update() {
update(true);
}
public static void update(boolean processMessages) {
try {
swapBuffers();
displayDirty = false;
} catch (LWJGLException e) {
throw new RuntimeException(e);
}
if (processMessages) processMessages();
}
public static void processMessages() {
glfwPollEvents();
Keyboard.poll();
Mouse.poll();
if (latestResized) {
latestResized = false;
displayResized = true;
displayWidth = latestWidth;
displayHeight = latestHeight;
} else {
displayResized = false;
}
}
public static void swapBuffers() throws LWJGLException {
glfwSwapBuffers(Window.handle);
}
public static void destroy() {
Window.releaseCallbacks();
glfwDestroyWindow(Window.handle);
/*try {
glfwTerminate();
} catch (Throwable t) {
t.printStackTrace();
}*/
displayCreated = false;
}
public static void setDisplayMode(DisplayMode dm) throws LWJGLException {
mode = dm;
}
public static DisplayMode getDisplayMode() {
return mode;
}
public static DisplayMode[] getAvailableDisplayModes() throws LWJGLException {
IntBuffer count = BufferUtils.createIntBuffer(1);
ByteBuffer modes = GLFW.glfwGetVideoModes(GLFW.glfwGetPrimaryMonitor(), count);
DisplayMode[] displayModes = new DisplayMode[count.get(0)];
for (int i = 0; i < count.get(0); i++) {
modes.position(i * GLFWvidmode.SIZEOF);
int w = GLFWvidmode.width(modes);
int h = GLFWvidmode.height(modes);
int b = GLFWvidmode.redBits(modes) + GLFWvidmode.greenBits(modes) + GLFWvidmode.blueBits(modes);
int r = GLFWvidmode.refreshRate(modes);
displayModes[i] = new DisplayMode(w, h, b, r);
}
return displayModes;
}
public static DisplayMode getDesktopDisplayMode() {
return desktopDisplayMode;
}
public static boolean wasResized() {
return displayResized;
}
public static int getX() {
return displayX;
}
public static int getY() {
return displayY;
}
public static int getWidth() {
return displayWidth;
}
public static int getHeight() {
return displayHeight;
}
public static int getFramebufferWidth() {
return displayFramebufferWidth;
}
public static int getFramebufferHeight() {
return displayFramebufferHeight;
}
public static void setTitle(String title) {
windowTitle = title;
}
public static boolean isCloseRequested() {
return glfwWindowShouldClose(Window.handle) == GL_TRUE;
}
public static boolean isDirty() {
return displayDirty;
}
public static void setInitialBackground(float red, float green, float blue) {
// TODO
System.out.println("TODO: Implement Display.setInitialBackground(float, float, float)");
}
public static int setIcon(java.nio.ByteBuffer[] icons) {
// TODO
System.out.println("TODO: Implement Display.setIcon(ByteBuffer[])");
return 0;
}
public static void setResizable(boolean resizable) {
displayResizable = resizable;
// TODO
}
public static boolean isResizable() {
return displayResizable;
}
public static void setDisplayModeAndFullscreen(DisplayMode mode) throws LWJGLException {
// TODO
System.out.println("TODO: Implement Display.setDisplayModeAndFullscreen(DisplayMode)");
}
public static void setFullscreen(boolean fullscreen) throws LWJGLException {
// TODO
}
public static boolean isFullscreen() {
// TODO
return false;
}
public static void setParent(java.awt.Canvas parent) throws LWJGLException {
// Do nothing as set parent not supported
}
public static void releaseContext() throws LWJGLException {
glfwMakeContextCurrent(0);
}
public static boolean isCurrent() throws LWJGLException {
return context.isCurrent();
}
public static void makeCurrent() throws LWJGLException {
glfwMakeContextCurrent(Window.handle);
}
public static java.lang.String getAdapter() {
// TODO
return "GeNotSupportedAdapter";
}
public static java.lang.String getVersion() {
// TODO
return "1.0 NOT SUPPORTED";
}
/**
* An accurate sync method that will attempt to run at a constant frame rate.
* It should be called once every frame.
*
* @param fps - the desired frame rate, in frames per second
*/
public static void sync(int fps) {
Sync.sync(fps);
}
public static Drawable getDrawable() {
return null;
}
static DisplayImplementation getImplementation() {
return null;
}
private static class Window {
static long handle;
static GLFWKeyCallback keyCallback;
static GLFWCharCallback charCallback;
static GLFWCursorPosCallback cursorPosCallback;
static GLFWMouseButtonCallback mouseButtonCallback;
static GLFWWindowFocusCallback windowFocusCallback;
static GLFWWindowIconifyCallback windowIconifyCallback;
static GLFWWindowSizeCallback windowSizeCallback;
static GLFWWindowPosCallback windowPosCallback;
static GLFWWindowRefreshCallback windowRefreshCallback;
static GLFWFramebufferSizeCallback framebufferSizeCallback;
public static void setCallbacks() {
glfwSetCallback(handle, keyCallback);
glfwSetCallback(handle, charCallback);
glfwSetCallback(handle, cursorPosCallback);
glfwSetCallback(handle, mouseButtonCallback);
glfwSetCallback(handle, windowFocusCallback);
glfwSetCallback(handle, windowIconifyCallback);
glfwSetCallback(handle, windowSizeCallback);
glfwSetCallback(handle, windowPosCallback);
glfwSetCallback(handle, windowRefreshCallback);
glfwSetCallback(handle, framebufferSizeCallback);
}
public static void releaseCallbacks() {
keyCallback.release();
charCallback.release();
cursorPosCallback.release();
mouseButtonCallback.release();
windowFocusCallback.release();
windowIconifyCallback.release();
windowSizeCallback.release();
windowPosCallback.release();
windowRefreshCallback.release();
framebufferSizeCallback.release();
}
}
}
@@ -37,164 +37,168 @@ package org.lwjglx.opengl;
* for each supported platform.
* @author elias_naur
*/
import java.awt.Canvas;
import java.nio.ByteBuffer;
import java.nio.FloatBuffer;
import java.nio.IntBuffer;
import java.awt.Canvas;
import org.lwjglx.LWJGLException;
interface DisplayImplementation extends InputImplementation {
void createWindow(DrawableLWJGL drawable, DisplayMode mode, Canvas parent, int x, int y) throws LWJGLException;
void createWindow(DrawableLWJGL drawable, DisplayMode mode, Canvas parent, int x, int y) throws LWJGLException;
void destroyWindow();
void destroyWindow();
void switchDisplayMode(DisplayMode mode) throws LWJGLException;
void switchDisplayMode(DisplayMode mode) throws LWJGLException;
/**
* Reset the display mode to whatever it was when LWJGL was initialized.
* Fails silently.
*/
void resetDisplayMode();
/**
* Reset the display mode to whatever it was when LWJGL was initialized.
* Fails silently.
*/
void resetDisplayMode();
/**
* Return the length of the gamma ramp arrays. Returns 0 if gamma settings are
* unsupported.
*
* @return the length of each gamma ramp array, or 0 if gamma settings are unsupported.
*/
int getGammaRampLength();
/**
* Return the length of the gamma ramp arrays. Returns 0 if gamma settings are
* unsupported.
*
* @return the length of each gamma ramp array, or 0 if gamma settings are unsupported.
*/
int getGammaRampLength();
/**
* Method to set the gamma ramp.
*/
void setGammaRamp(FloatBuffer gammaRamp) throws LWJGLException;
/**
* Method to set the gamma ramp.
*/
void setGammaRamp(FloatBuffer gammaRamp) throws LWJGLException;
/**
* Get the driver adapter string. This is a unique string describing the actual card's hardware, eg. "Geforce2", "PS2",
* "Radeon9700". If the adapter cannot be determined, this function returns null.
* @return a String
*/
String getAdapter();
/**
* Get the driver adapter string. This is a unique string describing the actual card's hardware, eg. "Geforce2", "PS2",
* "Radeon9700". If the adapter cannot be determined, this function returns null.
* @return a String
*/
String getAdapter();
/**
* Get the driver version. This is a vendor/adapter specific version string. If the version cannot be determined,
* this function returns null.
* @return a String
*/
String getVersion();
/**
* Get the driver version. This is a vendor/adapter specific version string. If the version cannot be determined,
* this function returns null.
* @return a String
*/
String getVersion();
/**
* Initialize and return the current display mode.
*/
DisplayMode init() throws LWJGLException;
/**
* Initialize and return the current display mode.
*/
DisplayMode init() throws LWJGLException;
/**
* Implementation of setTitle(). This will read the window's title member
* and stash it in the native title of the window.
*/
void setTitle(String title);
/**
* Implementation of setTitle(). This will read the window's title member
* and stash it in the native title of the window.
*/
void setTitle(String title);
boolean isCloseRequested();
boolean isCloseRequested();
boolean isVisible();
boolean isActive();
boolean isVisible();
boolean isDirty();
boolean isActive();
/**
* Create the native PeerInfo.
* @throws LWJGLException
*/
PeerInfo createPeerInfo(PixelFormat pixel_format, ContextAttribs attribs) throws LWJGLException;
boolean isDirty();
// void destroyPeerInfo();
/**
* Create the native PeerInfo.
* @throws LWJGLException
*/
PeerInfo createPeerInfo(PixelFormat pixel_format, ContextAttribs attribs) throws LWJGLException;
/**
* Updates the windows internal state. This must be called at least once per video frame
* to handle window close requests, moves, paints, etc.
*/
void update();
// void destroyPeerInfo();
void reshape(int x, int y, int width, int height);
/**
* Updates the windows internal state. This must be called at least once per video frame
* to handle window close requests, moves, paints, etc.
*/
void update();
/**
* Method for getting displaymodes
*/
DisplayMode[] getAvailableDisplayModes() throws LWJGLException;
void reshape(int x, int y, int width, int height);
/* Pbuffer */
int getPbufferCapabilities();
/**
* Method for getting displaymodes
*/
DisplayMode[] getAvailableDisplayModes() throws LWJGLException;
/**
* Method to test for buffer integrity
*/
boolean isBufferLost(PeerInfo handle);
/* Pbuffer */
int getPbufferCapabilities();
/**
* Method to create a Pbuffer
*/
PeerInfo createPbuffer(int width, int height, PixelFormat pixel_format, ContextAttribs attribs,
IntBuffer pixelFormatCaps,
IntBuffer pBufferAttribs) throws LWJGLException;
/**
* Method to test for buffer integrity
*/
boolean isBufferLost(PeerInfo handle);
void setPbufferAttrib(PeerInfo handle, int attrib, int value);
/**
* Method to create a Pbuffer
*/
PeerInfo createPbuffer(
int width,
int height,
PixelFormat pixel_format,
ContextAttribs attribs,
IntBuffer pixelFormatCaps,
IntBuffer pBufferAttribs)
throws LWJGLException;
void bindTexImageToPbuffer(PeerInfo handle, int buffer);
void setPbufferAttrib(PeerInfo handle, int attrib, int value);
void releaseTexImageFromPbuffer(PeerInfo handle, int buffer);
void bindTexImageToPbuffer(PeerInfo handle, int buffer);
/**
* Sets one or more icons for the Display.
* <ul>
* <li>On Windows you should supply at least one 16x16 icon and one 32x32.</li>
* <li>Linux (and similar platforms) expect one 32x32 icon.</li>
* <li>Mac OS X should be supplied one 128x128 icon</li>
* </ul>
* The implementation will use the supplied ByteBuffers with image data in RGBA and perform any conversions nescesarry for the specific platform.
*
* @param icons Array of icons in RGBA mode
* @return number of icons used.
*/
int setIcon(ByteBuffer[] icons);
void releaseTexImageFromPbuffer(PeerInfo handle, int buffer);
/**
* Enable or disable the Display window to be resized.
*
* @param resizable set to true to make the Display window resizable;
* false to disable resizing on the Display window.
*/
void setResizable(boolean resizable);
/**
* Sets one or more icons for the Display.
* <ul>
* <li>On Windows you should supply at least one 16x16 icon and one 32x32.</li>
* <li>Linux (and similar platforms) expect one 32x32 icon.</li>
* <li>Mac OS X should be supplied one 128x128 icon</li>
* </ul>
* The implementation will use the supplied ByteBuffers with image data in RGBA and perform any conversions nescesarry for the specific platform.
*
* @param icons Array of icons in RGBA mode
* @return number of icons used.
*/
int setIcon(ByteBuffer[] icons);
/**
* @return true if the Display window has been resized since this method was last called.
*/
boolean wasResized();
/**
* Enable or disable the Display window to be resized.
*
* @param resizable set to true to make the Display window resizable;
* false to disable resizing on the Display window.
*/
void setResizable(boolean resizable);
/**
* @return this method will return the width of the Display window.
*/
int getWidth();
/**
* @return true if the Display window has been resized since this method was last called.
*/
boolean wasResized();
/**
* @return this method will return the height of the Display window.
*/
int getHeight();
/**
* @return this method will return the top-left x position of the Display window.
*/
int getX();
/**
* @return this method will return the width of the Display window.
*/
int getWidth();
/**
* @return this method will return the top-left y position of the Display window.
*/
int getY();
/**
* @return this method will return the pixel scale factor of the Display window useful for high resolution modes.
*/
float getPixelScaleFactor();
/**
* @return this method will return the height of the Display window.
*/
int getHeight();
/**
* @return this method will return the top-left x position of the Display window.
*/
int getX();
/**
* @return this method will return the top-left y position of the Display window.
*/
int getY();
/**
* @return this method will return the pixel scale factor of the Display window useful for high resolution modes.
*/
float getPixelScaleFactor();
}
@@ -41,102 +41,98 @@ package org.lwjglx.opengl;
* @version $Revision$
* $Id$
*/
public final class DisplayMode {
/** properties of the display mode */
private final int width, height, bpp, freq;
/** If true, this instance can be used for fullscreen modes */
private final boolean fullscreen;
/** properties of the display mode */
private final int width, height, bpp, freq;
/** If true, this instance can be used for fullscreen modes */
private final boolean fullscreen;
/**
* Construct a display mode. DisplayModes constructed through the
* public constructor can only be used to specify the dimensions of
* the Display in windowed mode. To get the available DisplayModes for
* fullscreen modes, use Display.getAvailableDisplayModes().
*
* @param width The Display width.
* @param height The Display height.
* @see Display
*/
public DisplayMode(int width, int height) {
this(width, height, 0, 0, false);
}
/**
* Construct a display mode. DisplayModes constructed through the
* public constructor can only be used to specify the dimensions of
* the Display in windowed mode. To get the available DisplayModes for
* fullscreen modes, use Display.getAvailableDisplayModes().
*
* @param width The Display width.
* @param height The Display height.
* @see Display
*/
public DisplayMode(int width, int height) {
this(width, height, 0, 0, false);
}
DisplayMode(int width, int height, int bpp, int freq) {
this(width, height, bpp, freq, true);
}
DisplayMode(int width, int height, int bpp, int freq) {
this(width, height, bpp, freq, true);
}
private DisplayMode(int width, int height, int bpp, int freq, boolean fullscreen) {
this.width = width;
this.height = height;
this.bpp = bpp;
this.freq = freq;
this.fullscreen = fullscreen;
}
private DisplayMode(int width, int height, int bpp, int freq, boolean fullscreen) {
this.width = width;
this.height = height;
this.bpp = bpp;
this.freq = freq;
this.fullscreen = fullscreen;
}
/** True if this instance can be used for fullscreen modes */
public boolean isFullscreenCapable() {
return fullscreen;
}
/** True if this instance can be used for fullscreen modes */
public boolean isFullscreenCapable() {
return fullscreen;
}
public int getWidth() {
return width;
}
public int getWidth() {
return width;
}
public int getHeight() {
return height;
}
public int getHeight() {
return height;
}
public int getBitsPerPixel() {
return bpp;
}
public int getBitsPerPixel() {
return bpp;
}
public int getFrequency() {
return freq;
}
public int getFrequency() {
return freq;
}
/**
* Tests for <code>DisplayMode</code> equality
*
* @see java.lang.Object#equals(Object)
*/
public boolean equals(Object obj) {
if (obj == null || !(obj instanceof DisplayMode)) {
return false;
}
/**
* Tests for <code>DisplayMode</code> equality
*
* @see java.lang.Object#equals(Object)
*/
public boolean equals(Object obj) {
if (obj == null || !(obj instanceof DisplayMode)) {
return false;
}
DisplayMode dm = (DisplayMode) obj;
return dm.width == width
&& dm.height == height
&& dm.bpp == bpp
&& dm.freq == freq;
}
DisplayMode dm = (DisplayMode) obj;
return dm.width == width && dm.height == height && dm.bpp == bpp && dm.freq == freq;
}
/**
* Retrieves the hashcode for this object
*
* @see java.lang.Object#hashCode()
*/
public int hashCode() {
return width ^ height ^ freq ^ bpp;
}
/**
* Retrieves the hashcode for this object
*
* @see java.lang.Object#hashCode()
*/
public int hashCode() {
return width ^ height ^ freq ^ bpp;
}
/**
* Retrieves a String representation of this <code>DisplayMode</code>
*
* @see java.lang.Object#toString()
*/
public String toString() {
StringBuilder sb = new StringBuilder(32);
sb.append(width);
sb.append(" x ");
sb.append(height);
sb.append(" x ");
sb.append(bpp);
sb.append(" @");
sb.append(freq);
sb.append("Hz");
return sb.toString();
}
/**
* Retrieves a String representation of this <code>DisplayMode</code>
*
* @see java.lang.Object#toString()
*/
public String toString() {
StringBuilder sb = new StringBuilder(32);
sb.append(width);
sb.append(" x ");
sb.append(height);
sb.append(" x ");
sb.append(bpp);
sb.append(" @");
sb.append(freq);
sb.append("Hz");
return sb.toString();
}
}
+26 -28
View File
@@ -40,38 +40,36 @@ import org.lwjglx.PointerBuffer;
*
* @author elias_naur
*/
public interface Drawable {
/** Returns true if the Drawable's context is current in the current thread. */
boolean isCurrent() throws LWJGLException;
/** Returns true if the Drawable's context is current in the current thread. */
boolean isCurrent() throws LWJGLException;
/**
* Makes the Drawable's context current in the current thread.
*
* @throws LWJGLException
*/
void makeCurrent() throws LWJGLException;
/**
* Makes the Drawable's context current in the current thread.
*
* @throws LWJGLException
*/
void makeCurrent() throws LWJGLException;
/**
* If the Drawable's context is current in the current thread, no context will be current after a call to this method.
*
* @throws LWJGLException
*/
void releaseContext() throws LWJGLException;
/**
* If the Drawable's context is current in the current thread, no context will be current after a call to this method.
*
* @throws LWJGLException
*/
void releaseContext() throws LWJGLException;
/** Destroys the Drawable. */
void destroy();
/**
* Sets the appropriate khr_gl_sharing properties in the target <code>PointerBuffer</code>,
* so that if it is used in a <code>clCreateContext(FromType)</code> call, the created CL
* context will be sharing objects with this <code>Drawable</code>'s GL context. After a
* call to this method, the target buffer position will have advanced by 2 to 4 positions,
* depending on the implementation.
*
* @param properties The target properties buffer. It must have at least 4 positions remaining.
*/
void setCLSharingProperties(PointerBuffer properties) throws LWJGLException;
/** Destroys the Drawable. */
void destroy();
/**
* Sets the appropriate khr_gl_sharing properties in the target <code>PointerBuffer</code>,
* so that if it is used in a <code>clCreateContext(FromType)</code> call, the created CL
* context will be sharing objects with this <code>Drawable</code>'s GL context. After a
* call to this method, the target buffer position will have advanced by 2 to 4 positions,
* depending on the implementation.
*
* @param properties The target properties buffer. It must have at least 4 positions remaining.
*/
void setCLSharingProperties(PointerBuffer properties) throws LWJGLException;
}
+89 -94
View File
@@ -31,126 +31,121 @@
*/
package org.lwjglx.opengl;
import static org.lwjgl.opengl.GL11.*;
import org.lwjglx.LWJGLException;
import org.lwjglx.LWJGLUtil;
import org.lwjglx.PointerBuffer;
import static org.lwjgl.opengl.GL11.*;
/** @author Spasi */
abstract class DrawableGL implements DrawableLWJGL {
/** The PixelFormat used to create the drawable. */
protected PixelFormat pixel_format;
/** The PixelFormat used to create the drawable. */
protected PixelFormat pixel_format;
/** Handle to the native GL rendering context */
protected PeerInfo peer_info;
/** Handle to the native GL rendering context */
protected PeerInfo peer_info;
/** The OpenGL Context. */
protected ContextGL context;
/** The OpenGL Context. */
protected ContextGL context;
protected DrawableGL() {
}
protected DrawableGL() {}
public void setPixelFormat(final PixelFormatLWJGL pf) throws LWJGLException {
throw new UnsupportedOperationException();
}
public void setPixelFormat(final PixelFormatLWJGL pf) throws LWJGLException {
throw new UnsupportedOperationException();
}
public void setPixelFormat(final PixelFormatLWJGL pf, final ContextAttribs attribs) throws LWJGLException {
this.pixel_format = (PixelFormat)pf;
//this.peer_info = Display.getImplementation().createPeerInfo(pixel_format, attribs);
}
public void setPixelFormat(final PixelFormatLWJGL pf, final ContextAttribs attribs) throws LWJGLException {
this.pixel_format = (PixelFormat) pf;
// this.peer_info = Display.getImplementation().createPeerInfo(pixel_format, attribs);
}
public PixelFormatLWJGL getPixelFormat() {
return pixel_format;
}
public PixelFormatLWJGL getPixelFormat() {
return pixel_format;
}
public ContextGL getContext() {
synchronized ( GlobalLock.lock ) {
return context;
}
}
public ContextGL getContext() {
synchronized (GlobalLock.lock) {
return context;
}
}
public ContextGL createSharedContext() throws LWJGLException {
synchronized ( GlobalLock.lock ) {
//checkDestroyed();
//return new ContextGL(peer_info, context.getContextAttribs(), context);
return null;
}
}
public ContextGL createSharedContext() throws LWJGLException {
synchronized (GlobalLock.lock) {
// checkDestroyed();
// return new ContextGL(peer_info, context.getContextAttribs(), context);
return null;
}
}
public void checkGLError() {
Util.checkGLError();
}
public void checkGLError() {
Util.checkGLError();
}
public void setSwapInterval(final int swap_interval) {
ContextGL.setSwapInterval(swap_interval);
}
public void setSwapInterval(final int swap_interval) {
ContextGL.setSwapInterval(swap_interval);
}
public void swapBuffers() throws LWJGLException {
ContextGL.swapBuffers();
}
public void swapBuffers() throws LWJGLException {
ContextGL.swapBuffers();
}
public void initContext(final float r, final float g, final float b) {
// set background clear color
glClearColor(r, g, b, 0.0f);
// Clear window to avoid the desktop "showing through"
glClear(GL_COLOR_BUFFER_BIT);
}
public void initContext(final float r, final float g, final float b) {
// set background clear color
glClearColor(r, g, b, 0.0f);
// Clear window to avoid the desktop "showing through"
glClear(GL_COLOR_BUFFER_BIT);
}
public boolean isCurrent() throws LWJGLException {
synchronized ( GlobalLock.lock ) {
checkDestroyed();
return context.isCurrent();
}
}
public boolean isCurrent() throws LWJGLException {
synchronized (GlobalLock.lock) {
checkDestroyed();
return context.isCurrent();
}
}
public void makeCurrent() throws LWJGLException {
synchronized ( GlobalLock.lock ) {
checkDestroyed();
context.makeCurrent();
}
}
public void makeCurrent() throws LWJGLException {
synchronized (GlobalLock.lock) {
checkDestroyed();
context.makeCurrent();
}
}
public void releaseContext() throws LWJGLException {
synchronized ( GlobalLock.lock ) {
checkDestroyed();
if ( context.isCurrent() )
context.releaseCurrent();
}
}
public void releaseContext() throws LWJGLException {
synchronized (GlobalLock.lock) {
checkDestroyed();
if (context.isCurrent()) context.releaseCurrent();
}
}
public void destroy() {
synchronized ( GlobalLock.lock ) {
if ( context == null )
return;
public void destroy() {
synchronized (GlobalLock.lock) {
if (context == null) return;
try {
releaseContext();
try {
releaseContext();
context.forceDestroy();
context = null;
context.forceDestroy();
context = null;
if ( peer_info != null ) {
peer_info.destroy();
peer_info = null;
}
} catch (LWJGLException e) {
LWJGLUtil.log("Exception occurred while destroying Drawable: " + e);
}
}
}
if (peer_info != null) {
peer_info.destroy();
peer_info = null;
}
} catch (LWJGLException e) {
LWJGLUtil.log("Exception occurred while destroying Drawable: " + e);
}
}
}
public void setCLSharingProperties(final PointerBuffer properties) throws LWJGLException {
synchronized ( GlobalLock.lock ) {
checkDestroyed();
context.setCLSharingProperties(properties);
}
}
protected final void checkDestroyed() {
if ( context == null )
throw new IllegalStateException("The Drawable has no context available.");
}
public void setCLSharingProperties(final PointerBuffer properties) throws LWJGLException {
synchronized (GlobalLock.lock) {
checkDestroyed();
context.setCLSharingProperties(properties);
}
}
protected final void checkDestroyed() {
if (context == null) throw new IllegalStateException("The Drawable has no context available.");
}
}
@@ -40,32 +40,31 @@ import org.lwjglx.LWJGLException;
*/
interface DrawableLWJGL extends Drawable {
void setPixelFormat(PixelFormatLWJGL pf) throws LWJGLException;
void setPixelFormat(PixelFormatLWJGL pf) throws LWJGLException;
void setPixelFormat(PixelFormatLWJGL pf, ContextAttribs attribs) throws LWJGLException;
void setPixelFormat(PixelFormatLWJGL pf, ContextAttribs attribs) throws LWJGLException;
PixelFormatLWJGL getPixelFormat();
PixelFormatLWJGL getPixelFormat();
/**
* [INTERNAL USE ONLY] Returns the Drawable's Context.
*
* @return the Drawable's Context
*/
Context getContext();
/**
* [INTERNAL USE ONLY] Returns the Drawable's Context.
*
* @return the Drawable's Context
*/
Context getContext();
/**
* [INTERNAL USE ONLY] Creates a new Context that is shared with the Drawable's Context.
*
* @return a Context shared with the Drawable's Context.
*/
Context createSharedContext() throws LWJGLException;
/**
* [INTERNAL USE ONLY] Creates a new Context that is shared with the Drawable's Context.
*
* @return a Context shared with the Drawable's Context.
*/
Context createSharedContext() throws LWJGLException;
void checkGLError();
void checkGLError();
void setSwapInterval(int swap_interval);
void setSwapInterval(int swap_interval);
void swapBuffers() throws LWJGLException;
void swapBuffers() throws LWJGLException;
void initContext(final float r, final float g, final float b);
}
void initContext(final float r, final float g, final float b);
}
+8 -10
View File
@@ -1,20 +1,18 @@
package org.lwjglx.opengl;
import java.nio.ByteBuffer;
import org.lwjgl.BufferUtils;
import org.lwjgl.PointerBuffer;
import org.lwjgl.opengl.GL15;
public class GL15x {
public static ByteBuffer glGetBufferPointer(int target, int pname) {
int size = GL15.glGetBufferParameteri(target, GL15.GL_BUFFER_SIZE);
PointerBuffer pb = BufferUtils.createPointerBuffer(1);
GL15.glGetBufferPointer(target, pname, pb);
return pb.getByteBuffer(0, size);
}
public static ByteBuffer glGetBufferPointer(int target, int pname) {
int size = GL15.glGetBufferParameteri(target, GL15.GL_BUFFER_SIZE);
PointerBuffer pb = BufferUtils.createPointerBuffer(1);
GL15.glGetBufferPointer(target, pname, pb);
return pb.getByteBuffer(0, size);
}
}
+42 -49
View File
@@ -3,7 +3,6 @@ package org.lwjglx.opengl;
import java.nio.ByteBuffer;
import java.nio.IntBuffer;
import java.nio.ShortBuffer;
import org.lwjgl.BufferUtils;
import org.lwjgl.PointerBuffer;
import org.lwjgl.opengl.GL11;
@@ -11,53 +10,47 @@ import org.lwjgl.opengl.GL20;
import org.lwjgl.system.MemoryUtil;
public class GL20x {
public static void glVertexAttribPointer(int index, int size,
boolean unsigned, boolean normalized,
int stride, ByteBuffer buffer) {
int type = unsigned ? GL11.GL_UNSIGNED_BYTE : GL11.GL_BYTE;
GL20.glVertexAttribPointer(index, size, type, normalized, stride, buffer);
}
public static void glVertexAttribPointer(int index, int size,
boolean unsigned, boolean normalized,
int stride, ShortBuffer buffer) {
int type = unsigned ? GL11.GL_UNSIGNED_SHORT : GL11.GL_SHORT;
GL20.nglVertexAttribPointer(index, size, type, normalized, stride, MemoryUtil.memAddress(buffer));
}
public static void glVertexAttribPointer(int index, int size,
boolean unsigned, boolean normalized,
int stride, IntBuffer buffer) {
int type = unsigned ? GL11.GL_UNSIGNED_INT : GL11.GL_INT;
GL20.nglVertexAttribPointer(index, size, type, normalized, stride, MemoryUtil.memAddress(buffer));
}
public static String glGetActiveAttrib(int program, int index, int maxLength,
IntBuffer sizeType) {
//TODO check if correct
IntBuffer type = BufferUtils.createIntBuffer(1);
String s = GL20.glGetActiveAttrib(program, index, maxLength, sizeType, type);
sizeType.put(type.get(0));
return s;
}
public static String glGetActiveUniform(int program, int index, int maxLength,
IntBuffer sizeType) {
//TODO if correct
IntBuffer type = BufferUtils.createIntBuffer(1);
String s = GL20.glGetActiveUniform(program, index, maxLength, sizeType, type);
sizeType.put(type.get(0));
return s;
}
public static void glShaderSource(int shader, java.nio.ByteBuffer string) {
PointerBuffer strings = BufferUtils.createPointerBuffer(1);
IntBuffer lengths = BufferUtils.createIntBuffer(1);
strings.put(0, string);
lengths.put(0, new String(string.array()).length());//source.length());
org.lwjgl.opengl.GL20.glShaderSource(shader, strings, lengths);
}
public static void glVertexAttribPointer(
int index, int size, boolean unsigned, boolean normalized, int stride, ByteBuffer buffer) {
int type = unsigned ? GL11.GL_UNSIGNED_BYTE : GL11.GL_BYTE;
GL20.glVertexAttribPointer(index, size, type, normalized, stride, buffer);
}
public static void glVertexAttribPointer(
int index, int size, boolean unsigned, boolean normalized, int stride, ShortBuffer buffer) {
int type = unsigned ? GL11.GL_UNSIGNED_SHORT : GL11.GL_SHORT;
GL20.nglVertexAttribPointer(index, size, type, normalized, stride, MemoryUtil.memAddress(buffer));
}
public static void glVertexAttribPointer(
int index, int size, boolean unsigned, boolean normalized, int stride, IntBuffer buffer) {
int type = unsigned ? GL11.GL_UNSIGNED_INT : GL11.GL_INT;
GL20.nglVertexAttribPointer(index, size, type, normalized, stride, MemoryUtil.memAddress(buffer));
}
public static String glGetActiveAttrib(int program, int index, int maxLength, IntBuffer sizeType) {
// TODO check if correct
IntBuffer type = BufferUtils.createIntBuffer(1);
String s = GL20.glGetActiveAttrib(program, index, maxLength, sizeType, type);
sizeType.put(type.get(0));
return s;
}
public static String glGetActiveUniform(int program, int index, int maxLength, IntBuffer sizeType) {
// TODO if correct
IntBuffer type = BufferUtils.createIntBuffer(1);
String s = GL20.glGetActiveUniform(program, index, maxLength, sizeType, type);
sizeType.put(type.get(0));
return s;
}
public static void glShaderSource(int shader, java.nio.ByteBuffer string) {
PointerBuffer strings = BufferUtils.createPointerBuffer(1);
IntBuffer lengths = BufferUtils.createIntBuffer(1);
strings.put(0, string);
lengths.put(0, new String(string.array()).length()); // source.length());
org.lwjgl.opengl.GL20.glShaderSource(shader, strings, lengths);
}
}
@@ -1,11 +1,10 @@
package org.lwjglx.opengl;
public class GLContext {
private static ContextCapabilities contextCapabilities = new ContextCapabilities();
public static ContextCapabilities getCapabilities() {
return contextCapabilities;
}
private static ContextCapabilities contextCapabilities = new ContextCapabilities();
public static ContextCapabilities getCapabilities() {
return contextCapabilities;
}
}
+4 -5
View File
@@ -40,8 +40,7 @@ import org.lwjglx.PointerWrapperAbstract;
*/
public final class GLSync extends PointerWrapperAbstract {
GLSync(final long sync) {
super(sync);
}
}
GLSync(final long sync) {
super(sync);
}
}
@@ -36,5 +36,5 @@ package org.lwjglx.opengl;
* synchronize access to Display.
*/
final class GlobalLock {
static final Object lock = new Object();
static final Object lock = new Object();
}
@@ -37,98 +37,98 @@ package org.lwjglx.opengl;
* for each supported platform.
* @author elias_naur
*/
import java.nio.ByteBuffer;
import java.nio.IntBuffer;
import org.lwjglx.LWJGLException;
public interface InputImplementation {
/*
* Mouse methods
*/
/** Query of wheel support */
boolean hasWheel();
/*
* Mouse methods
*/
/** Query of wheel support */
boolean hasWheel();
/** Query of button count */
int getButtonCount();
/** Query of button count */
int getButtonCount();
/**
* Method to create the mouse.
*/
void createMouse() throws LWJGLException;
/**
* Method to create the mouse.
*/
void createMouse() throws LWJGLException;
/**
* Method the destroy the mouse
*/
void destroyMouse();
/**
* Method the destroy the mouse
*/
void destroyMouse();
/**
* Method to poll the mouse
*/
void pollMouse(IntBuffer coord_buffer, ByteBuffer buttons);
/**
* Method to poll the mouse
*/
void pollMouse(IntBuffer coord_buffer, ByteBuffer buttons);
/**
* Method to read the keyboard buffer
*/
void readMouse(ByteBuffer buffer);
/**
* Method to read the keyboard buffer
*/
void readMouse(ByteBuffer buffer);
void grabMouse(boolean grab);
void grabMouse(boolean grab);
/**
* Function to determine native cursor support
*/
int getNativeCursorCapabilities();
/**
* Function to determine native cursor support
*/
int getNativeCursorCapabilities();
/** Method to set the native cursor position */
void setCursorPosition(int x, int y);
/** Method to set the native cursor */
void setNativeCursor(Object handle) throws LWJGLException;
/** Method to set the native cursor position */
void setCursorPosition(int x, int y);
/** Method returning the minimum cursor size */
int getMinCursorSize();
/** Method to set the native cursor */
void setNativeCursor(Object handle) throws LWJGLException;
/** Method returning the maximum cursor size */
int getMaxCursorSize();
/** Method returning the minimum cursor size */
int getMinCursorSize();
/*
* Keyboard methods
*/
/** Method returning the maximum cursor size */
int getMaxCursorSize();
/**
* Method to create the keyboard
*/
void createKeyboard() throws LWJGLException;
/*
* Keyboard methods
*/
/**
* Method to destroy the keyboard
*/
void destroyKeyboard();
/**
* Method to create the keyboard
*/
void createKeyboard() throws LWJGLException;
/**
* Method to poll the keyboard.
*
* @param keyDownBuffer the address of a 256-byte buffer to place
* key states in.
*/
void pollKeyboard(ByteBuffer keyDownBuffer);
/**
* Method to destroy the keyboard
*/
void destroyKeyboard();
/**
* Method to read the keyboard buffer
*/
void readKeyboard(ByteBuffer buffer);
/**
* Method to poll the keyboard.
*
* @param keyDownBuffer the address of a 256-byte buffer to place
* key states in.
*/
void pollKeyboard(ByteBuffer keyDownBuffer);
// int isStateKeySet(int key);
/**
* Method to read the keyboard buffer
*/
void readKeyboard(ByteBuffer buffer);
/** Native cursor handles */
Object createCursor(int width, int height, int xHotspot, int yHotspot, int numImages, IntBuffer images, IntBuffer delays) throws LWJGLException;
// int isStateKeySet(int key);
void destroyCursor(Object cursor_handle);
/** Native cursor handles */
Object createCursor(
int width, int height, int xHotspot, int yHotspot, int numImages, IntBuffer images, IntBuffer delays)
throws LWJGLException;
int getWidth();
void destroyCursor(Object cursor_handle);
int getHeight();
int getWidth();
boolean isInsideWindow();
int getHeight();
boolean isInsideWindow();
}
@@ -41,49 +41,48 @@ package org.lwjglx.opengl;
*/
public class OpenGLException extends RuntimeException {
private static final long serialVersionUID = 1L;
private static final long serialVersionUID = 1L;
/** Constructor for OpenGLException. */
public OpenGLException(int gl_error_code) {
this(createErrorMessage(gl_error_code));
}
/** Constructor for OpenGLException. */
public OpenGLException(int gl_error_code) {
this(createErrorMessage(gl_error_code));
}
private static String createErrorMessage(int gl_error_code) {
String error_string = Util.translateGLErrorString(gl_error_code);
return error_string + " (" + gl_error_code + ")";
}
private static String createErrorMessage(int gl_error_code) {
String error_string = Util.translateGLErrorString(gl_error_code);
return error_string + " (" + gl_error_code + ")";
}
/** Constructor for OpenGLException. */
public OpenGLException() {
super();
}
/** Constructor for OpenGLException. */
public OpenGLException() {
super();
}
/**
* Constructor for OpenGLException.
*
* @param message
*/
public OpenGLException(String message) {
super(message);
}
/**
* Constructor for OpenGLException.
*
* @param message
*/
public OpenGLException(String message) {
super(message);
}
/**
* Constructor for OpenGLException.
*
* @param message
* @param cause
*/
public OpenGLException(String message, Throwable cause) {
super(message, cause);
}
/**
* Constructor for OpenGLException.
*
* @param cause
*/
public OpenGLException(Throwable cause) {
super(cause);
}
/**
* Constructor for OpenGLException.
*
* @param message
* @param cause
*/
public OpenGLException(String message, Throwable cause) {
super(message, cause);
}
/**
* Constructor for OpenGLException.
*
* @param cause
*/
public OpenGLException(Throwable cause) {
super(cause);
}
}
+251 -238
View File
@@ -32,7 +32,6 @@
package org.lwjglx.opengl;
import java.nio.IntBuffer;
import org.lwjglx.BufferUtils;
import org.lwjglx.LWJGLException;
import org.lwjglx.Sys;
@@ -49,272 +48,286 @@ import org.lwjglx.Sys;
* $Id$
*/
public final class Pbuffer extends DrawableGL {
/**
* Indicates that Pbuffers can be created.
*/
public static final int PBUFFER_SUPPORTED = 0;// mark as not supported 1 << 0;
/**
* Indicates that Pbuffers can be created.
*/
public static final int PBUFFER_SUPPORTED = 0; // mark as not supported 1 << 0;
/**
* Indicates that Pbuffers can be used as render-textures.
*/
public static final int RENDER_TEXTURE_SUPPORTED = 1 << 1;
/**
* Indicates that Pbuffers can be used as render-textures.
*/
public static final int RENDER_TEXTURE_SUPPORTED = 1 << 1;
/**
* Indicates that Pbuffers can be used as non-power-of-two render-textures.
*/
public static final int RENDER_TEXTURE_RECTANGLE_SUPPORTED = 1 << 2;
/**
* Indicates that Pbuffers can be used as non-power-of-two render-textures.
*/
public static final int RENDER_TEXTURE_RECTANGLE_SUPPORTED = 1 << 2;
/**
* Indicates that Pbuffers can be used as depth render-textures.
*/
public static final int RENDER_DEPTH_TEXTURE_SUPPORTED = 1 << 3;
/**
* Indicates that Pbuffers can be used as depth render-textures.
*/
public static final int RENDER_DEPTH_TEXTURE_SUPPORTED = 1 << 3;
/**
* The render-to-texture mipmap level attribute.
*/
public static final int MIPMAP_LEVEL = RenderTexture.WGL_MIPMAP_LEVEL_ARB;
/**
* The render-to-texture mipmap level attribute.
*/
public static final int MIPMAP_LEVEL = RenderTexture.WGL_MIPMAP_LEVEL_ARB;
/**
* The render-to-texture cube map face attribute.
*/
public static final int CUBE_MAP_FACE = RenderTexture.WGL_CUBE_MAP_FACE_ARB;
/**
* The render-to-texture cube map face attribute.
*/
public static final int CUBE_MAP_FACE = RenderTexture.WGL_CUBE_MAP_FACE_ARB;
/**
* The render-to-texture cube map positive X face value.
*/
public static final int TEXTURE_CUBE_MAP_POSITIVE_X = RenderTexture.WGL_TEXTURE_CUBE_MAP_POSITIVE_X_ARB;
/**
* The render-to-texture cube map positive X face value.
*/
public static final int TEXTURE_CUBE_MAP_POSITIVE_X = RenderTexture.WGL_TEXTURE_CUBE_MAP_POSITIVE_X_ARB;
/**
* The render-to-texture cube map negative X face value.
*/
public static final int TEXTURE_CUBE_MAP_NEGATIVE_X = RenderTexture.WGL_TEXTURE_CUBE_MAP_NEGATIVE_X_ARB;
/**
* The render-to-texture cube map negative X face value.
*/
public static final int TEXTURE_CUBE_MAP_NEGATIVE_X = RenderTexture.WGL_TEXTURE_CUBE_MAP_NEGATIVE_X_ARB;
/**
* The render-to-texture cube map positive Y face value.
*/
public static final int TEXTURE_CUBE_MAP_POSITIVE_Y = RenderTexture.WGL_TEXTURE_CUBE_MAP_POSITIVE_Y_ARB;
/**
* The render-to-texture cube map positive Y face value.
*/
public static final int TEXTURE_CUBE_MAP_POSITIVE_Y = RenderTexture.WGL_TEXTURE_CUBE_MAP_POSITIVE_Y_ARB;
/**
* The render-to-texture cube map negative Y face value.
*/
public static final int TEXTURE_CUBE_MAP_NEGATIVE_Y = RenderTexture.WGL_TEXTURE_CUBE_MAP_NEGATIVE_Y_ARB;
/**
* The render-to-texture cube map negative Y face value.
*/
public static final int TEXTURE_CUBE_MAP_NEGATIVE_Y = RenderTexture.WGL_TEXTURE_CUBE_MAP_NEGATIVE_Y_ARB;
/**
* The render-to-texture cube map positive Z face value.
*/
public static final int TEXTURE_CUBE_MAP_POSITIVE_Z = RenderTexture.WGL_TEXTURE_CUBE_MAP_POSITIVE_Z_ARB;
/**
* The render-to-texture cube map positive Z face value.
*/
public static final int TEXTURE_CUBE_MAP_POSITIVE_Z = RenderTexture.WGL_TEXTURE_CUBE_MAP_POSITIVE_Z_ARB;
/**
* The render-to-texture cube map negative Z face value.
*/
public static final int TEXTURE_CUBE_MAP_NEGATIVE_Z = RenderTexture.WGL_TEXTURE_CUBE_MAP_NEGATIVE_Z_ARB;
/**
* The render-to-texture cube map negative Z face value.
*/
public static final int TEXTURE_CUBE_MAP_NEGATIVE_Z = RenderTexture.WGL_TEXTURE_CUBE_MAP_NEGATIVE_Z_ARB;
/**
* The Pbuffer front left buffer.
*/
public static final int FRONT_LEFT_BUFFER = RenderTexture.WGL_FRONT_LEFT_ARB;
/**
* The Pbuffer front left buffer.
*/
public static final int FRONT_LEFT_BUFFER = RenderTexture.WGL_FRONT_LEFT_ARB;
/**
* The Pbuffer front right buffer.
*/
public static final int FRONT_RIGHT_BUFFER = RenderTexture.WGL_FRONT_RIGHT_ARB;
/**
* The Pbuffer front right buffer.
*/
public static final int FRONT_RIGHT_BUFFER = RenderTexture.WGL_FRONT_RIGHT_ARB;
/**
* The Pbuffer back left buffer.
*/
public static final int BACK_LEFT_BUFFER = RenderTexture.WGL_BACK_LEFT_ARB;
/**
* The Pbuffer back left buffer.
*/
public static final int BACK_LEFT_BUFFER = RenderTexture.WGL_BACK_LEFT_ARB;
/**
* The Pbuffer back right buffer.
*/
public static final int BACK_RIGHT_BUFFER = RenderTexture.WGL_BACK_RIGHT_ARB;
/**
* The Pbuffer back right buffer.
*/
public static final int BACK_RIGHT_BUFFER = RenderTexture.WGL_BACK_RIGHT_ARB;
/**
* The Pbuffer depth buffer.
*/
public static final int DEPTH_BUFFER = RenderTexture.WGL_DEPTH_COMPONENT_NV;
/**
* The Pbuffer depth buffer.
*/
public static final int DEPTH_BUFFER = RenderTexture.WGL_DEPTH_COMPONENT_NV;
/**
* Width
*/
private final int width;
/**
* Width
*/
private final int width;
/**
* Height
*/
private final int height;
/**
* Height
*/
private final int height;
static {
Sys.initialize();
}
static {
Sys.initialize();
}
/**
* Create an instance of a Pbuffer with a unique OpenGL context. The buffer is single-buffered.
* <p/>
* NOTE: The Pbuffer will have its own context that shares display lists and textures with <code>shared_context</code>,
* or, if <code>shared_context</code> is <code>null</code>, the Display context if it is created. The Pbuffer
* will have its own OpenGL state. Therefore, state changes to a pbuffer will not be seen in the window context and vice versa.
* <p/>
*
* @param width Pbuffer width
* @param height Pbuffer height
* @param pixel_format Minimum Pbuffer context properties
* @param shared_drawable If non-null the Pbuffer will share display lists and textures with it. Otherwise, the Pbuffer will share
* with the Display context (if created).
*/
public Pbuffer(int width, int height, PixelFormat pixel_format, Drawable shared_drawable) throws LWJGLException {
this(width, height, pixel_format, null, shared_drawable);
}
/**
* Create an instance of a Pbuffer with a unique OpenGL context. The buffer is single-buffered.
* <p/>
* NOTE: The Pbuffer will have its own context that shares display lists and textures with <code>shared_context</code>,
* or, if <code>shared_context</code> is <code>null</code>, the Display context if it is created. The Pbuffer
* will have its own OpenGL state. Therefore, state changes to a pbuffer will not be seen in the window context and vice versa.
* <p/>
*
* @param width Pbuffer width
* @param height Pbuffer height
* @param pixel_format Minimum Pbuffer context properties
* @param shared_drawable If non-null the Pbuffer will share display lists and textures with it. Otherwise, the Pbuffer will share
* with the Display context (if created).
*/
public Pbuffer(int width, int height, PixelFormat pixel_format, Drawable shared_drawable) throws LWJGLException {
this(width, height, pixel_format, null, shared_drawable);
}
/**
* Create an instance of a Pbuffer with a unique OpenGL context. The buffer is single-buffered.
* <p/>
* NOTE: The Pbuffer will have its own context that shares display lists and textures with <code>shared_context</code>,
* or, if <code>shared_context</code> is <code>null</code>, the Display context if it is created. The Pbuffer
* will have its own OpenGL state. Therefore, state changes to a pbuffer will not be seen in the window context and vice versa.
* <p/>
* The renderTexture parameter defines the necessary state for enabling render-to-texture. When this parameter is null,
* render-to-texture is not available. Before using render-to-texture, the Pbuffer capabilities must be queried to ensure that
* it is supported. Currently only windows platform can support this feature, so it is recommended that EXT_framebuffer_object
* or similar is used if available, for maximum portability.
* <p/>
*
* @param width Pbuffer width
* @param height Pbuffer height
* @param pixel_format Minimum Pbuffer context properties
* @param renderTexture
* @param shared_drawable If non-null the Pbuffer will share display lists and textures with it. Otherwise, the Pbuffer will share
* with the Display context (if created).
*/
public Pbuffer(int width, int height, PixelFormat pixel_format, RenderTexture renderTexture, Drawable shared_drawable) throws LWJGLException {
this(width, height, pixel_format, renderTexture, shared_drawable, null);
}
/**
* Create an instance of a Pbuffer with a unique OpenGL context. The buffer is single-buffered.
* <p/>
* NOTE: The Pbuffer will have its own context that shares display lists and textures with <code>shared_context</code>,
* or, if <code>shared_context</code> is <code>null</code>, the Display context if it is created. The Pbuffer
* will have its own OpenGL state. Therefore, state changes to a pbuffer will not be seen in the window context and vice versa.
* <p/>
* The renderTexture parameter defines the necessary state for enabling render-to-texture. When this parameter is null,
* render-to-texture is not available. Before using render-to-texture, the Pbuffer capabilities must be queried to ensure that
* it is supported. Currently only windows platform can support this feature, so it is recommended that EXT_framebuffer_object
* or similar is used if available, for maximum portability.
* <p/>
*
* @param width Pbuffer width
* @param height Pbuffer height
* @param pixel_format Minimum Pbuffer context properties
* @param renderTexture
* @param shared_drawable If non-null the Pbuffer will share display lists and textures with it. Otherwise, the Pbuffer will share
* with the Display context (if created).
*/
public Pbuffer(
int width, int height, PixelFormat pixel_format, RenderTexture renderTexture, Drawable shared_drawable)
throws LWJGLException {
this(width, height, pixel_format, renderTexture, shared_drawable, null);
}
/**
* Create an instance of a Pbuffer with a unique OpenGL context. The buffer is single-buffered.
* <p/>
* NOTE: The Pbuffer will have its own context that shares display lists and textures with <code>shared_context</code>,
* or, if <code>shared_context</code> is <code>null</code>, the Display context if it is created. The Pbuffer
* will have its own OpenGL state. Therefore, state changes to a pbuffer will not be seen in the window context and vice versa.
* <p/>
* The renderTexture parameter defines the necessary state for enabling render-to-texture. When this parameter is null,
* render-to-texture is not available. Before using render-to-texture, the Pbuffer capabilities must be queried to ensure that
* it is supported. Currently only windows platform can support this feature, so it is recommended that EXT_framebuffer_object
* or similar is used if available, for maximum portability.
* <p/>
*
* @param width Pbuffer width
* @param height Pbuffer height
* @param pixel_format Minimum Pbuffer context properties
* @param renderTexture
* @param shared_drawable If non-null the Pbuffer will share display lists and textures with it. Otherwise, the Pbuffer will share
* with the Display context (if created).
* @param attribs The ContextAttribs to use when creating the context. (optional, may be null)
*/
public Pbuffer(int width, int height, PixelFormat pixel_format, RenderTexture renderTexture, Drawable shared_drawable, ContextAttribs attribs) throws LWJGLException {
if (pixel_format == null)
throw new NullPointerException("Pixel format must be non-null");
this.width = width;
this.height = height;
this.peer_info = createPbuffer(width, height, pixel_format, attribs, renderTexture);
Context shared_context = null;
if ( shared_drawable == null )
shared_drawable = Display.getDrawable(); // May be null
if (shared_drawable != null)
shared_context = ((DrawableLWJGL)shared_drawable).getContext();
//this.context = new ContextGL(peer_info, attribs, (ContextGL)shared_context);
}
/**
* Create an instance of a Pbuffer with a unique OpenGL context. The buffer is single-buffered.
* <p/>
* NOTE: The Pbuffer will have its own context that shares display lists and textures with <code>shared_context</code>,
* or, if <code>shared_context</code> is <code>null</code>, the Display context if it is created. The Pbuffer
* will have its own OpenGL state. Therefore, state changes to a pbuffer will not be seen in the window context and vice versa.
* <p/>
* The renderTexture parameter defines the necessary state for enabling render-to-texture. When this parameter is null,
* render-to-texture is not available. Before using render-to-texture, the Pbuffer capabilities must be queried to ensure that
* it is supported. Currently only windows platform can support this feature, so it is recommended that EXT_framebuffer_object
* or similar is used if available, for maximum portability.
* <p/>
*
* @param width Pbuffer width
* @param height Pbuffer height
* @param pixel_format Minimum Pbuffer context properties
* @param renderTexture
* @param shared_drawable If non-null the Pbuffer will share display lists and textures with it. Otherwise, the Pbuffer will share
* with the Display context (if created).
* @param attribs The ContextAttribs to use when creating the context. (optional, may be null)
*/
public Pbuffer(
int width,
int height,
PixelFormat pixel_format,
RenderTexture renderTexture,
Drawable shared_drawable,
ContextAttribs attribs)
throws LWJGLException {
if (pixel_format == null) throw new NullPointerException("Pixel format must be non-null");
this.width = width;
this.height = height;
this.peer_info = createPbuffer(width, height, pixel_format, attribs, renderTexture);
Context shared_context = null;
if (shared_drawable == null) shared_drawable = Display.getDrawable(); // May be null
if (shared_drawable != null) shared_context = ((DrawableLWJGL) shared_drawable).getContext();
// this.context = new ContextGL(peer_info, attribs, (ContextGL)shared_context);
}
private static PeerInfo createPbuffer(int width, int height, PixelFormat pixel_format, ContextAttribs attribs, RenderTexture renderTexture) throws LWJGLException {
if ( renderTexture == null ) {
// Though null is a perfectly valid argument, Matrox Parhelia drivers expect
// a 0 terminated list, or else they crash. Supplying NULL or 0, should
// cause the drivers to use default settings
IntBuffer defaultAttribs = BufferUtils.createIntBuffer(1);
return Display.getImplementation().createPbuffer(width, height, pixel_format, attribs, null, defaultAttribs);
} else
return Display.getImplementation().createPbuffer(width, height, pixel_format, attribs,
renderTexture.pixelFormatCaps,
renderTexture.pBufferAttribs);
}
private static PeerInfo createPbuffer(
int width, int height, PixelFormat pixel_format, ContextAttribs attribs, RenderTexture renderTexture)
throws LWJGLException {
if (renderTexture == null) {
// Though null is a perfectly valid argument, Matrox Parhelia drivers expect
// a 0 terminated list, or else they crash. Supplying NULL or 0, should
// cause the drivers to use default settings
IntBuffer defaultAttribs = BufferUtils.createIntBuffer(1);
return Display.getImplementation()
.createPbuffer(width, height, pixel_format, attribs, null, defaultAttribs);
} else
return Display.getImplementation()
.createPbuffer(
width,
height,
pixel_format,
attribs,
renderTexture.pixelFormatCaps,
renderTexture.pBufferAttribs);
}
/**
* Method to test for validity of the buffer. If this function returns true, the buffer contents is lost. The buffer can still
* be used, but the results are undefined. The application is expected to release the buffer if needed, destroy it and recreate
* a new buffer.
*
* @return true if the buffer is lost and destroyed, false if the buffer is valid.
*/
public synchronized boolean isBufferLost() {
checkDestroyed();
return Display.getImplementation().isBufferLost(peer_info);
}
/**
* Method to test for validity of the buffer. If this function returns true, the buffer contents is lost. The buffer can still
* be used, but the results are undefined. The application is expected to release the buffer if needed, destroy it and recreate
* a new buffer.
*
* @return true if the buffer is lost and destroyed, false if the buffer is valid.
*/
public synchronized boolean isBufferLost() {
checkDestroyed();
return Display.getImplementation().isBufferLost(peer_info);
}
/**
* Gets the Pbuffer capabilities.
*
* @return a bitmask of Pbuffer capabilities.
*/
public static int getCapabilities() {
return Display.getImplementation().getPbufferCapabilities();
}
/**
* Gets the Pbuffer capabilities.
*
* @return a bitmask of Pbuffer capabilities.
*/
public static int getCapabilities() {
return Display.getImplementation().getPbufferCapabilities();
}
// -----------------------------------------------------------------------------------------
// ------------------------------- Render-to-Texture Methods -------------------------------
// -----------------------------------------------------------------------------------------
// -----------------------------------------------------------------------------------------
// ------------------------------- Render-to-Texture Methods -------------------------------
// -----------------------------------------------------------------------------------------
/**
* Sets a render-to-texture attribute.
* <p/>
* The attrib parameter can be one of MIPMAP_LEVEL and CUBE_MAP_FACE. When the attrib parameter is CUBE_MAP_FACE then the value
* parameter can be on of the following:
* <p/>
* TEXTURE_CUBE_MAP_POSITIVE_X TEXTURE_CUBE_MAP_NEGATIVE_X TEXTURE_CUBE_MAP_POSITIVE_Y TEXTURE_CUBE_MAP_NEGATIVE_Y
* TEXTURE_CUBE_MAP_POSITIVE_Z TEXTURE_CUBE_MAP_NEGATIVE_Z
*
* @param attrib
* @param value
*/
public synchronized void setAttrib(int attrib, int value) {
checkDestroyed();
Display.getImplementation().setPbufferAttrib(peer_info, attrib, value);
}
/**
* Sets a render-to-texture attribute.
* <p/>
* The attrib parameter can be one of MIPMAP_LEVEL and CUBE_MAP_FACE. When the attrib parameter is CUBE_MAP_FACE then the value
* parameter can be on of the following:
* <p/>
* TEXTURE_CUBE_MAP_POSITIVE_X TEXTURE_CUBE_MAP_NEGATIVE_X TEXTURE_CUBE_MAP_POSITIVE_Y TEXTURE_CUBE_MAP_NEGATIVE_Y
* TEXTURE_CUBE_MAP_POSITIVE_Z TEXTURE_CUBE_MAP_NEGATIVE_Z
*
* @param attrib
* @param value
*/
public synchronized void setAttrib(int attrib, int value) {
checkDestroyed();
Display.getImplementation().setPbufferAttrib(peer_info, attrib, value);
}
/**
* Binds the currently bound texture to the buffer specified. The buffer can be one of the following:
* <p/>
* FRONT_LEFT_BUFFER FRONT_RIGHT_BUFFER BACK_LEFT_BUFFER BACK_RIGHT_BUFFER DEPTH_BUFFER
*
* @param buffer
*/
public synchronized void bindTexImage(int buffer) {
checkDestroyed();
Display.getImplementation().bindTexImageToPbuffer(peer_info, buffer);
}
/**
* Binds the currently bound texture to the buffer specified. The buffer can be one of the following:
* <p/>
* FRONT_LEFT_BUFFER FRONT_RIGHT_BUFFER BACK_LEFT_BUFFER BACK_RIGHT_BUFFER DEPTH_BUFFER
*
* @param buffer
*/
public synchronized void bindTexImage(int buffer) {
checkDestroyed();
Display.getImplementation().bindTexImageToPbuffer(peer_info, buffer);
}
/**
* Releases the currently bound texture from the buffer specified.
*
* @param buffer
*/
public synchronized void releaseTexImage(int buffer) {
checkDestroyed();
Display.getImplementation().releaseTexImageFromPbuffer(peer_info, buffer);
}
/**
* Releases the currently bound texture from the buffer specified.
*
* @param buffer
*/
public synchronized void releaseTexImage(int buffer) {
checkDestroyed();
Display.getImplementation().releaseTexImageFromPbuffer(peer_info, buffer);
}
/**
* @return Returns the height.
*/
public synchronized int getHeight() {
checkDestroyed();
return height;
}
/**
* @return Returns the height.
*/
public synchronized int getHeight() {
checkDestroyed();
return height;
}
/**
* @return Returns the width.
*/
public synchronized int getWidth() {
checkDestroyed();
return width;
}
/**
* @return Returns the width.
*/
public synchronized int getWidth() {
checkDestroyed();
return width;
}
}
+43 -45
View File
@@ -32,7 +32,6 @@
package org.lwjglx.opengl;
import java.nio.ByteBuffer;
import org.lwjglx.LWJGLException;
import org.lwjglx.LWJGLUtil;
@@ -43,55 +42,54 @@ import org.lwjglx.LWJGLUtil;
* $Id$
*/
abstract class PeerInfo {
private final ByteBuffer handle;
private Thread locking_thread; // Thread that has locked this PeerInfo
private int lock_count;
private final ByteBuffer handle;
private Thread locking_thread; // Thread that has locked this PeerInfo
private int lock_count;
protected PeerInfo(ByteBuffer handle) {
this.handle = handle;
}
protected PeerInfo(ByteBuffer handle) {
this.handle = handle;
}
private void lockAndInitHandle() throws LWJGLException {
doLockAndInitHandle();
}
private void lockAndInitHandle() throws LWJGLException {
doLockAndInitHandle();
}
public final synchronized void unlock() throws LWJGLException {
if (lock_count <= 0)
throw new IllegalStateException("PeerInfo not locked!");
if (Thread.currentThread() != locking_thread)
throw new IllegalStateException("PeerInfo already locked by " + locking_thread);
lock_count--;
if (lock_count == 0) {
doUnlock();
locking_thread = null;
notify();
}
}
public final synchronized void unlock() throws LWJGLException {
if (lock_count <= 0) throw new IllegalStateException("PeerInfo not locked!");
if (Thread.currentThread() != locking_thread)
throw new IllegalStateException("PeerInfo already locked by " + locking_thread);
lock_count--;
if (lock_count == 0) {
doUnlock();
locking_thread = null;
notify();
}
}
protected abstract void doLockAndInitHandle() throws LWJGLException;
protected abstract void doUnlock() throws LWJGLException;
protected abstract void doLockAndInitHandle() throws LWJGLException;
public final synchronized ByteBuffer lockAndGetHandle() throws LWJGLException {
Thread this_thread = Thread.currentThread();
while (locking_thread != null && locking_thread != this_thread) {
try {
wait();
} catch (InterruptedException e) {
LWJGLUtil.log("Interrupted while waiting for PeerInfo lock: " + e);
}
}
if (lock_count == 0) {
locking_thread = this_thread;
doLockAndInitHandle();
}
lock_count++;
return getHandle();
}
protected abstract void doUnlock() throws LWJGLException;
protected final ByteBuffer getHandle() {
return handle;
}
public final synchronized ByteBuffer lockAndGetHandle() throws LWJGLException {
Thread this_thread = Thread.currentThread();
while (locking_thread != null && locking_thread != this_thread) {
try {
wait();
} catch (InterruptedException e) {
LWJGLUtil.log("Interrupted while waiting for PeerInfo lock: " + e);
}
}
if (lock_count == 0) {
locking_thread = this_thread;
doLockAndInitHandle();
}
lock_count++;
return getHandle();
}
public void destroy() {
}
protected final ByteBuffer getHandle() {
return handle;
}
public void destroy() {}
}
+339 -322
View File
@@ -49,376 +49,393 @@ package org.lwjglx.opengl;
*/
public final class PixelFormat implements PixelFormatLWJGL {
/**
* The number of bits per pixel, exluding alpha.
* This parameter is ignored in Display.create().
*/
private int bpp;
/** The number of alpha bits. */
private int alpha;
/** The number of depth buffer bits */
private int depth;
/** The number of stencil bits */
private int stencil;
/**
* The number of samples to use in anti-aliasing.
* 0 means that anti-aliasing is disabled.
*/
private int samples;
/**
* The number of COLOR_SAMPLES_NV to use for Coverage Sample Anti-aliasing (CSAA).
* When this number is greater than 0, the {@code samples} property will be treated
* as if it were the COVERAGE_SAMPLES_NV property.
* <p/>
* This property is currently a no-op for the MacOS implementation.
*/
private int colorSamples;
/** The number of auxiliary buffers */
private int num_aux_buffers;
/** The number of bits per pixel in the accumulation buffer */
private int accum_bpp;
/** The number of alpha bits in the accumulation buffer */
private int accum_alpha;
/** Whether this format requires a stereo buffer */
private boolean stereo;
/** Whether this format specifies a floating point format */
private boolean floating_point;
/**
* Whether this format specifies a packed floating point format (32 bit unsigned - R11F_G11F_B10F)
* This property is currently a no-op for the MacOS implementation.
*/
private boolean floating_point_packed;
/**
* Whether this format specifies an sRGB format
* This property is currently a no-op for the MacOS implementation.
*/
private boolean sRGB;
/**
* The number of bits per pixel, exluding alpha.
* This parameter is ignored in Display.create().
*/
private int bpp;
/** The number of alpha bits. */
private int alpha;
/** The number of depth buffer bits */
private int depth;
/** The number of stencil bits */
private int stencil;
/**
* The number of samples to use in anti-aliasing.
* 0 means that anti-aliasing is disabled.
*/
private int samples;
/**
* The number of COLOR_SAMPLES_NV to use for Coverage Sample Anti-aliasing (CSAA).
* When this number is greater than 0, the {@code samples} property will be treated
* as if it were the COVERAGE_SAMPLES_NV property.
* <p/>
* This property is currently a no-op for the MacOS implementation.
*/
private int colorSamples;
/** The number of auxiliary buffers */
private int num_aux_buffers;
/** The number of bits per pixel in the accumulation buffer */
private int accum_bpp;
/** The number of alpha bits in the accumulation buffer */
private int accum_alpha;
/** Whether this format requires a stereo buffer */
private boolean stereo;
/** Whether this format specifies a floating point format */
private boolean floating_point;
/**
* Whether this format specifies a packed floating point format (32 bit unsigned - R11F_G11F_B10F)
* This property is currently a no-op for the MacOS implementation.
*/
private boolean floating_point_packed;
/**
* Whether this format specifies an sRGB format
* This property is currently a no-op for the MacOS implementation.
*/
private boolean sRGB;
/**
* Default pixel format is minimum 8 bits depth, and no alpha
* nor stencil requirements.
*/
public PixelFormat() {
this(0, 8, 0);
}
/**
* Default pixel format is minimum 8 bits depth, and no alpha
* nor stencil requirements.
*/
public PixelFormat() {
this(0, 8, 0);
}
public PixelFormat(int alpha, int depth, int stencil) {
this(alpha, depth, stencil, 0);
}
public PixelFormat(int alpha, int depth, int stencil) {
this(alpha, depth, stencil, 0);
}
public PixelFormat(int alpha, int depth, int stencil, int samples) {
this(0, alpha, depth, stencil, samples);
}
public PixelFormat(int alpha, int depth, int stencil, int samples) {
this(0, alpha, depth, stencil, samples);
}
public PixelFormat(int bpp, int alpha, int depth, int stencil, int samples) {
this(bpp, alpha, depth, stencil, samples, 0, 0, 0, false);
}
public PixelFormat(int bpp, int alpha, int depth, int stencil, int samples) {
this(bpp, alpha, depth, stencil, samples, 0, 0, 0, false);
}
public PixelFormat(int bpp, int alpha, int depth, int stencil, int samples, int num_aux_buffers, int accum_bpp, int accum_alpha, boolean stereo) {
this(bpp, alpha, depth, stencil, samples, num_aux_buffers, accum_bpp, accum_alpha, stereo, false);
}
public PixelFormat(
int bpp,
int alpha,
int depth,
int stencil,
int samples,
int num_aux_buffers,
int accum_bpp,
int accum_alpha,
boolean stereo) {
this(bpp, alpha, depth, stencil, samples, num_aux_buffers, accum_bpp, accum_alpha, stereo, false);
}
public PixelFormat(int bpp, int alpha, int depth, int stencil, int samples, int num_aux_buffers, int accum_bpp, int accum_alpha, boolean stereo, boolean floating_point) {
this.bpp = bpp;
this.alpha = alpha;
this.depth = depth;
this.stencil = stencil;
public PixelFormat(
int bpp,
int alpha,
int depth,
int stencil,
int samples,
int num_aux_buffers,
int accum_bpp,
int accum_alpha,
boolean stereo,
boolean floating_point) {
this.bpp = bpp;
this.alpha = alpha;
this.depth = depth;
this.stencil = stencil;
this.samples = samples;
this.samples = samples;
this.num_aux_buffers = num_aux_buffers;
this.num_aux_buffers = num_aux_buffers;
this.accum_bpp = accum_bpp;
this.accum_alpha = accum_alpha;
this.accum_bpp = accum_bpp;
this.accum_alpha = accum_alpha;
this.stereo = stereo;
this.stereo = stereo;
this.floating_point = floating_point;
this.floating_point_packed = false;
this.sRGB = false;
}
this.floating_point = floating_point;
this.floating_point_packed = false;
this.sRGB = false;
}
private PixelFormat(final PixelFormat pf) {
this.bpp = pf.bpp;
this.alpha = pf.alpha;
this.depth = pf.depth;
this.stencil = pf.stencil;
private PixelFormat(final PixelFormat pf) {
this.bpp = pf.bpp;
this.alpha = pf.alpha;
this.depth = pf.depth;
this.stencil = pf.stencil;
this.samples = pf.samples;
this.colorSamples = pf.colorSamples;
this.samples = pf.samples;
this.colorSamples = pf.colorSamples;
this.num_aux_buffers = pf.num_aux_buffers;
this.num_aux_buffers = pf.num_aux_buffers;
this.accum_bpp = pf.accum_bpp;
this.accum_alpha = pf.accum_alpha;
this.accum_bpp = pf.accum_bpp;
this.accum_alpha = pf.accum_alpha;
this.stereo = pf.stereo;
this.stereo = pf.stereo;
this.floating_point = pf.floating_point;
this.floating_point_packed = pf.floating_point_packed;
this.sRGB = pf.sRGB;
}
this.floating_point = pf.floating_point;
this.floating_point_packed = pf.floating_point_packed;
this.sRGB = pf.sRGB;
}
public int getBitsPerPixel() {
return bpp;
}
public int getBitsPerPixel() {
return bpp;
}
/**
* Returns a new PixelFormat object with the same properties as this PixelFormat and the new bits per pixel value.
*
* @param bpp the new bits per pixel value.
*
* @return the new PixelFormat
*/
public PixelFormat withBitsPerPixel(final int bpp) {
if ( bpp < 0 )
throw new IllegalArgumentException("Invalid number of bits per pixel specified: " + bpp);
/**
* Returns a new PixelFormat object with the same properties as this PixelFormat and the new bits per pixel value.
*
* @param bpp the new bits per pixel value.
*
* @return the new PixelFormat
*/
public PixelFormat withBitsPerPixel(final int bpp) {
if (bpp < 0) throw new IllegalArgumentException("Invalid number of bits per pixel specified: " + bpp);
final PixelFormat pf = new PixelFormat(this);
pf.bpp = bpp;
return pf;
}
final PixelFormat pf = new PixelFormat(this);
pf.bpp = bpp;
return pf;
}
public int getAlphaBits() {
return alpha;
}
public int getAlphaBits() {
return alpha;
}
/**
* Returns a new PixelFormat object with the same properties as this PixelFormat and the new alpha bits value.
*
* @param alpha the new alpha bits value.
*
* @return the new PixelFormat
*/
public PixelFormat withAlphaBits(final int alpha) {
if ( alpha < 0 )
throw new IllegalArgumentException("Invalid number of alpha bits specified: " + alpha);
/**
* Returns a new PixelFormat object with the same properties as this PixelFormat and the new alpha bits value.
*
* @param alpha the new alpha bits value.
*
* @return the new PixelFormat
*/
public PixelFormat withAlphaBits(final int alpha) {
if (alpha < 0) throw new IllegalArgumentException("Invalid number of alpha bits specified: " + alpha);
final PixelFormat pf = new PixelFormat(this);
pf.alpha = alpha;
return pf;
}
final PixelFormat pf = new PixelFormat(this);
pf.alpha = alpha;
return pf;
}
public int getDepthBits() {
return depth;
}
public int getDepthBits() {
return depth;
}
/**
* Returns a new PixelFormat object with the same properties as this PixelFormat and the new depth bits value.
*
* @param depth the new depth bits value.
*
* @return the new PixelFormat
*/
public PixelFormat withDepthBits(final int depth) {
if ( depth < 0 )
throw new IllegalArgumentException("Invalid number of depth bits specified: " + depth);
/**
* Returns a new PixelFormat object with the same properties as this PixelFormat and the new depth bits value.
*
* @param depth the new depth bits value.
*
* @return the new PixelFormat
*/
public PixelFormat withDepthBits(final int depth) {
if (depth < 0) throw new IllegalArgumentException("Invalid number of depth bits specified: " + depth);
final PixelFormat pf = new PixelFormat(this);
pf.depth = depth;
return pf;
}
final PixelFormat pf = new PixelFormat(this);
pf.depth = depth;
return pf;
}
public int getStencilBits() {
return stencil;
}
public int getStencilBits() {
return stencil;
}
/**
* Returns a new PixelFormat object with the same properties as this PixelFormat and the new stencil bits value.
*
* @param stencil the new stencil bits value.
*
* @return the new PixelFormat
*/
public PixelFormat withStencilBits(final int stencil) {
if ( stencil < 0 )
throw new IllegalArgumentException("Invalid number of stencil bits specified: " + stencil);
/**
* Returns a new PixelFormat object with the same properties as this PixelFormat and the new stencil bits value.
*
* @param stencil the new stencil bits value.
*
* @return the new PixelFormat
*/
public PixelFormat withStencilBits(final int stencil) {
if (stencil < 0) throw new IllegalArgumentException("Invalid number of stencil bits specified: " + stencil);
final PixelFormat pf = new PixelFormat(this);
pf.stencil = stencil;
return pf;
}
final PixelFormat pf = new PixelFormat(this);
pf.stencil = stencil;
return pf;
}
public int getSamples() {
return samples;
}
public int getSamples() {
return samples;
}
/**
* Returns a new PixelFormat object with the same properties as this PixelFormat and the new samples value.
*
* @param samples the new samples value.
*
* @return the new PixelFormat
*/
public PixelFormat withSamples(final int samples) {
if ( samples < 0 )
throw new IllegalArgumentException("Invalid number of samples specified: " + samples);
/**
* Returns a new PixelFormat object with the same properties as this PixelFormat and the new samples value.
*
* @param samples the new samples value.
*
* @return the new PixelFormat
*/
public PixelFormat withSamples(final int samples) {
if (samples < 0) throw new IllegalArgumentException("Invalid number of samples specified: " + samples);
final PixelFormat pf = new PixelFormat(this);
pf.samples = samples;
return pf;
}
final PixelFormat pf = new PixelFormat(this);
pf.samples = samples;
return pf;
}
/**
* Returns a new PixelFormat object with the same properties as this PixelFormat and the new color samples values.
* A value greater than 0 is valid only if the {@code samples} property is also greater than 0. Additionally, the
* color samples value needs to be lower than or equal to the {@code samples} property.
*
* @param colorSamples the new color samples value.
*
* @return the new PixelFormat
*/
public PixelFormat withCoverageSamples(final int colorSamples) {
return withCoverageSamples(colorSamples, samples);
}
/**
* Returns a new PixelFormat object with the same properties as this PixelFormat and the new color samples values.
* A value greater than 0 is valid only if the {@code samples} property is also greater than 0. Additionally, the
* color samples value needs to be lower than or equal to the {@code samples} property.
*
* @param colorSamples the new color samples value.
*
* @return the new PixelFormat
*/
public PixelFormat withCoverageSamples(final int colorSamples) {
return withCoverageSamples(colorSamples, samples);
}
/**
* Returns a new PixelFormat object with the same properties as this PixelFormat and the new color samples
* and coverage samples values.
*
* @param colorSamples the new color samples value. This value must be lower than or equal to the coverage samples value.
* @param coverageSamples the new coverage samples value.
*
* @return the new PixelFormat
*/
public PixelFormat withCoverageSamples(final int colorSamples, final int coverageSamples) {
if ( coverageSamples < 0 || colorSamples < 0 || (coverageSamples == 0 && 0 < colorSamples) || coverageSamples < colorSamples )
throw new IllegalArgumentException("Invalid number of coverage samples specified: " + coverageSamples + " - " + colorSamples);
/**
* Returns a new PixelFormat object with the same properties as this PixelFormat and the new color samples
* and coverage samples values.
*
* @param colorSamples the new color samples value. This value must be lower than or equal to the coverage samples value.
* @param coverageSamples the new coverage samples value.
*
* @return the new PixelFormat
*/
public PixelFormat withCoverageSamples(final int colorSamples, final int coverageSamples) {
if (coverageSamples < 0
|| colorSamples < 0
|| (coverageSamples == 0 && 0 < colorSamples)
|| coverageSamples < colorSamples)
throw new IllegalArgumentException(
"Invalid number of coverage samples specified: " + coverageSamples + " - " + colorSamples);
final PixelFormat pf = new PixelFormat(this);
pf.samples = coverageSamples;
pf.colorSamples = colorSamples;
return pf;
}
final PixelFormat pf = new PixelFormat(this);
pf.samples = coverageSamples;
pf.colorSamples = colorSamples;
return pf;
}
public int getAuxBuffers() {
return num_aux_buffers;
}
public int getAuxBuffers() {
return num_aux_buffers;
}
/**
* Returns a new PixelFormat object with the same properties as this PixelFormat and the new auxiliary buffers value.
*
* @param num_aux_buffers the new auxiliary buffers value.
*
* @return the new PixelFormat
*/
public PixelFormat withAuxBuffers(final int num_aux_buffers) {
if ( num_aux_buffers < 0 )
throw new IllegalArgumentException("Invalid number of auxiliary buffers specified: " + num_aux_buffers);
/**
* Returns a new PixelFormat object with the same properties as this PixelFormat and the new auxiliary buffers value.
*
* @param num_aux_buffers the new auxiliary buffers value.
*
* @return the new PixelFormat
*/
public PixelFormat withAuxBuffers(final int num_aux_buffers) {
if (num_aux_buffers < 0)
throw new IllegalArgumentException("Invalid number of auxiliary buffers specified: " + num_aux_buffers);
final PixelFormat pf = new PixelFormat(this);
pf.num_aux_buffers = num_aux_buffers;
return pf;
}
final PixelFormat pf = new PixelFormat(this);
pf.num_aux_buffers = num_aux_buffers;
return pf;
}
public int getAccumulationBitsPerPixel() {
return accum_bpp;
}
public int getAccumulationBitsPerPixel() {
return accum_bpp;
}
/**
* Returns a new PixelFormat object with the same properties as this PixelFormat and the new bits per pixel in the accumulation buffer value.
*
* @param accum_bpp the new bits per pixel in the accumulation buffer value.
*
* @return the new PixelFormat
*/
public PixelFormat withAccumulationBitsPerPixel(final int accum_bpp) {
if ( accum_bpp < 0 )
throw new IllegalArgumentException("Invalid number of bits per pixel in the accumulation buffer specified: " + accum_bpp);
/**
* Returns a new PixelFormat object with the same properties as this PixelFormat and the new bits per pixel in the accumulation buffer value.
*
* @param accum_bpp the new bits per pixel in the accumulation buffer value.
*
* @return the new PixelFormat
*/
public PixelFormat withAccumulationBitsPerPixel(final int accum_bpp) {
if (accum_bpp < 0)
throw new IllegalArgumentException(
"Invalid number of bits per pixel in the accumulation buffer specified: " + accum_bpp);
final PixelFormat pf = new PixelFormat(this);
pf.accum_bpp = accum_bpp;
return pf;
}
final PixelFormat pf = new PixelFormat(this);
pf.accum_bpp = accum_bpp;
return pf;
}
public int getAccumulationAlpha() {
return accum_alpha;
}
public int getAccumulationAlpha() {
return accum_alpha;
}
/**
* Returns a new PixelFormat object with the same properties as this PixelFormat and the new alpha bits in the accumulation buffer value.
*
* @param accum_alpha the new alpha bits in the accumulation buffer value.
*
* @return the new PixelFormat
*/
public PixelFormat withAccumulationAlpha(final int accum_alpha) {
if ( accum_alpha < 0 )
throw new IllegalArgumentException("Invalid number of alpha bits in the accumulation buffer specified: " + accum_alpha);
/**
* Returns a new PixelFormat object with the same properties as this PixelFormat and the new alpha bits in the accumulation buffer value.
*
* @param accum_alpha the new alpha bits in the accumulation buffer value.
*
* @return the new PixelFormat
*/
public PixelFormat withAccumulationAlpha(final int accum_alpha) {
if (accum_alpha < 0)
throw new IllegalArgumentException(
"Invalid number of alpha bits in the accumulation buffer specified: " + accum_alpha);
final PixelFormat pf = new PixelFormat(this);
pf.accum_alpha = accum_alpha;
return pf;
}
final PixelFormat pf = new PixelFormat(this);
pf.accum_alpha = accum_alpha;
return pf;
}
public boolean isStereo() {
return stereo;
}
public boolean isStereo() {
return stereo;
}
/**
* Returns a new PixelFormat object with the same properties as this PixelFormat and the new stereo value.
*
* @param stereo the new stereo value.
*
* @return the new PixelFormat
*/
public PixelFormat withStereo(final boolean stereo) {
final PixelFormat pf = new PixelFormat(this);
pf.stereo = stereo;
return pf;
}
/**
* Returns a new PixelFormat object with the same properties as this PixelFormat and the new stereo value.
*
* @param stereo the new stereo value.
*
* @return the new PixelFormat
*/
public PixelFormat withStereo(final boolean stereo) {
final PixelFormat pf = new PixelFormat(this);
pf.stereo = stereo;
return pf;
}
public boolean isFloatingPoint() {
return floating_point;
}
public boolean isFloatingPoint() {
return floating_point;
}
/**
* Returns a new PixelFormat object with the same properties as this PixelFormat and the new floating point value.
* If floating_point is true, floating_point_packed will be reset to false.
*
* @param floating_point the new floating point value.
*
* @return the new PixelFormat
*/
public PixelFormat withFloatingPoint(final boolean floating_point) {
final PixelFormat pf = new PixelFormat(this);
pf.floating_point = floating_point;
if ( floating_point )
pf.floating_point_packed = false;
return pf;
}
/**
* Returns a new PixelFormat object with the same properties as this PixelFormat and the new floating point value.
* If floating_point is true, floating_point_packed will be reset to false.
*
* @param floating_point the new floating point value.
*
* @return the new PixelFormat
*/
public PixelFormat withFloatingPoint(final boolean floating_point) {
final PixelFormat pf = new PixelFormat(this);
pf.floating_point = floating_point;
if (floating_point) pf.floating_point_packed = false;
return pf;
}
/**
* Returns a new PixelFormat object with the same properties as this PixelFormat and the new packed floating point value.
* If floating_point_packed is true, floating_point will be reset to false.
*
* @param floating_point_packed the new packed floating point value.
*
* @return the new PixelFormat
*/
public PixelFormat withFloatingPointPacked(final boolean floating_point_packed) {
final PixelFormat pf = new PixelFormat(this);
pf.floating_point_packed = floating_point_packed;
if ( floating_point_packed )
pf.floating_point = false;
return pf;
}
/**
* Returns a new PixelFormat object with the same properties as this PixelFormat and the new packed floating point value.
* If floating_point_packed is true, floating_point will be reset to false.
*
* @param floating_point_packed the new packed floating point value.
*
* @return the new PixelFormat
*/
public PixelFormat withFloatingPointPacked(final boolean floating_point_packed) {
final PixelFormat pf = new PixelFormat(this);
pf.floating_point_packed = floating_point_packed;
if (floating_point_packed) pf.floating_point = false;
return pf;
}
public boolean isSRGB() {
return sRGB;
}
public boolean isSRGB() {
return sRGB;
}
/**
* Returns a new PixelFormat object with the same properties as this PixelFormat and the new sRGB value.
*
* @param sRGB the new floating point value.
*
* @return the new PixelFormat
*/
public PixelFormat withSRGB(final boolean sRGB) {
final PixelFormat pf = new PixelFormat(this);
pf.sRGB = sRGB;
return pf;
}
}
/**
* Returns a new PixelFormat object with the same properties as this PixelFormat and the new sRGB value.
*
* @param sRGB the new floating point value.
*
* @return the new PixelFormat
*/
public PixelFormat withSRGB(final boolean sRGB) {
final PixelFormat pf = new PixelFormat(this);
pf.sRGB = sRGB;
return pf;
}
}
@@ -37,5 +37,5 @@ package org.lwjglx.opengl;
* @author Spasi
*/
public interface PixelFormatLWJGL {
// Marker interface
}
// Marker interface
}
+178 -180
View File
@@ -31,221 +31,219 @@
*/
package org.lwjglx.opengl;
import java.nio.IntBuffer;
import org.lwjgl.BufferUtils;
import static org.lwjgl.opengl.GL11.*;
import java.nio.IntBuffer;
import org.lwjgl.BufferUtils;
/** This class represents the state necessary for render-to-texture. */
public final class RenderTexture {
// ----------------------------------------------------------------------------------
// ----------------------------- WGL_ARB_render_texture -----------------------------
// ----------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------
// ----------------------------- WGL_ARB_render_texture -----------------------------
// ----------------------------------------------------------------------------------
/*
Accepted by the <piAttributes> parameter of wglGetPixelFormatAttribivARB,
wglGetPixelFormatAttribfvARB, and the <piAttribIList> and <pfAttribIList>
parameters of wglChoosePixelFormatARB:
*/
private static final int WGL_BIND_TO_TEXTURE_RGB_ARB = 0x2070;
private static final int WGL_BIND_TO_TEXTURE_RGBA_ARB = 0x2071;
/*
Accepted by the <piAttributes> parameter of wglGetPixelFormatAttribivARB,
wglGetPixelFormatAttribfvARB, and the <piAttribIList> and <pfAttribIList>
parameters of wglChoosePixelFormatARB:
*/
private static final int WGL_BIND_TO_TEXTURE_RGB_ARB = 0x2070;
private static final int WGL_BIND_TO_TEXTURE_RGBA_ARB = 0x2071;
/*
Accepted by the <piAttribList> parameter of wglCreatePbufferARB and
by the <iAttribute> parameter of wglQueryPbufferARB:
*/
private static final int WGL_TEXTURE_FORMAT_ARB = 0x2072;
private static final int WGL_TEXTURE_TARGET_ARB = 0x2073;
private static final int WGL_MIPMAP_TEXTURE_ARB = 0x2074;
/*
Accepted by the <piAttribList> parameter of wglCreatePbufferARB and
by the <iAttribute> parameter of wglQueryPbufferARB:
*/
private static final int WGL_TEXTURE_FORMAT_ARB = 0x2072;
private static final int WGL_TEXTURE_TARGET_ARB = 0x2073;
private static final int WGL_MIPMAP_TEXTURE_ARB = 0x2074;
/*
Accepted as a value in the <piAttribList> parameter of
wglCreatePbufferARB and returned in the value parameter of
wglQueryPbufferARB when <iAttribute> is WGL_TEXTURE_FORMAT_ARB:
*/
private static final int WGL_TEXTURE_RGB_ARB = 0x2075;
private static final int WGL_TEXTURE_RGBA_ARB = 0x2076;
/*
Accepted as a value in the <piAttribList> parameter of
wglCreatePbufferARB and returned in the value parameter of
wglQueryPbufferARB when <iAttribute> is WGL_TEXTURE_FORMAT_ARB:
*/
private static final int WGL_TEXTURE_RGB_ARB = 0x2075;
private static final int WGL_TEXTURE_RGBA_ARB = 0x2076;
/*
Accepted as a value in the <piAttribList> parameter of
wglCreatePbufferARB and returned in the value parameter of
wglQueryPbufferARB when <iAttribute> is WGL_TEXTURE_TARGET_ARB:
*/
private static final int WGL_TEXTURE_CUBE_MAP_ARB = 0x2078;
private static final int WGL_TEXTURE_1D_ARB = 0x2079;
private static final int WGL_TEXTURE_2D_ARB = 0x207A;
private static final int WGL_NO_TEXTURE_ARB = 0x2077;
/*
Accepted as a value in the <piAttribList> parameter of
wglCreatePbufferARB and returned in the value parameter of
wglQueryPbufferARB when <iAttribute> is WGL_TEXTURE_TARGET_ARB:
*/
private static final int WGL_TEXTURE_CUBE_MAP_ARB = 0x2078;
private static final int WGL_TEXTURE_1D_ARB = 0x2079;
private static final int WGL_TEXTURE_2D_ARB = 0x207A;
private static final int WGL_NO_TEXTURE_ARB = 0x2077;
/*
Accepted by the <piAttribList> parameter of wglSetPbufferAttribARB and
by the <iAttribute> parameter of wglQueryPbufferARB:
*/
static final int WGL_MIPMAP_LEVEL_ARB = 0x207B;
static final int WGL_CUBE_MAP_FACE_ARB = 0x207C;
/*
Accepted by the <piAttribList> parameter of wglSetPbufferAttribARB and
by the <iAttribute> parameter of wglQueryPbufferARB:
*/
static final int WGL_MIPMAP_LEVEL_ARB = 0x207B;
static final int WGL_CUBE_MAP_FACE_ARB = 0x207C;
/*
Accepted as a value in the <piAttribList> parameter of
wglSetPbufferAttribARB and returned in the value parameter of
wglQueryPbufferARB when <iAttribute> is WGL_CUBE_MAP_FACE_ARB:
*/
static final int WGL_TEXTURE_CUBE_MAP_POSITIVE_X_ARB = 0x207D;
static final int WGL_TEXTURE_CUBE_MAP_NEGATIVE_X_ARB = 0x207E;
static final int WGL_TEXTURE_CUBE_MAP_POSITIVE_Y_ARB = 0x207F;
static final int WGL_TEXTURE_CUBE_MAP_NEGATIVE_Y_ARB = 0x2080;
static final int WGL_TEXTURE_CUBE_MAP_POSITIVE_Z_ARB = 0x2081;
static final int WGL_TEXTURE_CUBE_MAP_NEGATIVE_Z_ARB = 0x2082;
/*
Accepted as a value in the <piAttribList> parameter of
wglSetPbufferAttribARB and returned in the value parameter of
wglQueryPbufferARB when <iAttribute> is WGL_CUBE_MAP_FACE_ARB:
*/
static final int WGL_TEXTURE_CUBE_MAP_POSITIVE_X_ARB = 0x207D;
static final int WGL_TEXTURE_CUBE_MAP_NEGATIVE_X_ARB = 0x207E;
static final int WGL_TEXTURE_CUBE_MAP_POSITIVE_Y_ARB = 0x207F;
static final int WGL_TEXTURE_CUBE_MAP_NEGATIVE_Y_ARB = 0x2080;
static final int WGL_TEXTURE_CUBE_MAP_POSITIVE_Z_ARB = 0x2081;
static final int WGL_TEXTURE_CUBE_MAP_NEGATIVE_Z_ARB = 0x2082;
/*
Accepted by the <iBuffer> parameter of wglBindTexImageARB and
wglReleaseTexImageARB:
*/
static final int WGL_FRONT_LEFT_ARB = 0x2083;
static final int WGL_FRONT_RIGHT_ARB = 0x2084;
static final int WGL_BACK_LEFT_ARB = 0x2085;
static final int WGL_BACK_RIGHT_ARB = 0x2086;
/*
Accepted by the <iBuffer> parameter of wglBindTexImageARB and
wglReleaseTexImageARB:
*/
static final int WGL_FRONT_LEFT_ARB = 0x2083;
static final int WGL_FRONT_RIGHT_ARB = 0x2084;
static final int WGL_BACK_LEFT_ARB = 0x2085;
static final int WGL_BACK_RIGHT_ARB = 0x2086;
/*
private static final int WGL_AUX0_ARB = 0x2087;
private static final int WGL_AUX1_ARB = 0x2088;
private static final int WGL_AUX2_ARB = 0x2089;
private static final int WGL_AUX3_ARB = 0x208A;
private static final int WGL_AUX4_ARB = 0x208B;
private static final int WGL_AUX5_ARB = 0x208C;
private static final int WGL_AUX6_ARB = 0x208D;
private static final int WGL_AUX7_ARB = 0x208E;
private static final int WGL_AUX8_ARB = 0x208F;
private static final int WGL_AUX9_ARB = 0x2090;
*/
/*
private static final int WGL_AUX0_ARB = 0x2087;
private static final int WGL_AUX1_ARB = 0x2088;
private static final int WGL_AUX2_ARB = 0x2089;
private static final int WGL_AUX3_ARB = 0x208A;
private static final int WGL_AUX4_ARB = 0x208B;
private static final int WGL_AUX5_ARB = 0x208C;
private static final int WGL_AUX6_ARB = 0x208D;
private static final int WGL_AUX7_ARB = 0x208E;
private static final int WGL_AUX8_ARB = 0x208F;
private static final int WGL_AUX9_ARB = 0x2090;
*/
// -------------------------------------------------------------------------------------------
// ----------------------------- WGL_NV_render_texture_rectangle -----------------------------
// -------------------------------------------------------------------------------------------
// -------------------------------------------------------------------------------------------
// ----------------------------- WGL_NV_render_texture_rectangle -----------------------------
// -------------------------------------------------------------------------------------------
/*
Accepted by the <piAttributes> parameter of wglGetPixelFormatAttribivARB,
wglGetPixelFormatAttribfvARB, and the <piAttribIList> and <pfAttribIList>
parameters of wglChoosePixelFormatARB:
*/
private static final int WGL_BIND_TO_TEXTURE_RECTANGLE_RGB_NV = 0x20A0;
private static final int WGL_BIND_TO_TEXTURE_RECTANGLE_RGBA_NV = 0x20A1;
/*
Accepted by the <piAttributes> parameter of wglGetPixelFormatAttribivARB,
wglGetPixelFormatAttribfvARB, and the <piAttribIList> and <pfAttribIList>
parameters of wglChoosePixelFormatARB:
*/
private static final int WGL_BIND_TO_TEXTURE_RECTANGLE_RGB_NV = 0x20A0;
private static final int WGL_BIND_TO_TEXTURE_RECTANGLE_RGBA_NV = 0x20A1;
/*
Accepted as a value in the <piAttribList> parameter of wglCreatePbufferARB
and returned in the value parameter of wglQueryPbufferARB when
<iAttribute> is WGL_TEXTURE_TARGET_ARB:
*/
private static final int WGL_TEXTURE_RECTANGLE_NV = 0x20A2;
/*
Accepted as a value in the <piAttribList> parameter of wglCreatePbufferARB
and returned in the value parameter of wglQueryPbufferARB when
<iAttribute> is WGL_TEXTURE_TARGET_ARB:
*/
private static final int WGL_TEXTURE_RECTANGLE_NV = 0x20A2;
// ---------------------------------------------------------------------------------------
// ----------------------------- WGL_NV_render_depth_texture -----------------------------
// ---------------------------------------------------------------------------------------
// ---------------------------------------------------------------------------------------
// ----------------------------- WGL_NV_render_depth_texture -----------------------------
// ---------------------------------------------------------------------------------------
/*
Accepted by the <piAttributes> parameter of wglGetPixelFormatAttribivARB,
wglGetPixelFormatAttribfvARB, and the <piAttribIList> and <pfAttribIList>
parameters of wglChoosePixelFormatARB:
*/
private static final int WGL_BIND_TO_TEXTURE_DEPTH_NV = 0x20A3;
private static final int WGL_BIND_TO_TEXTURE_RECTANGLE_DEPTH_NV = 0x20A4;
/*
Accepted by the <piAttributes> parameter of wglGetPixelFormatAttribivARB,
wglGetPixelFormatAttribfvARB, and the <piAttribIList> and <pfAttribIList>
parameters of wglChoosePixelFormatARB:
*/
private static final int WGL_BIND_TO_TEXTURE_DEPTH_NV = 0x20A3;
private static final int WGL_BIND_TO_TEXTURE_RECTANGLE_DEPTH_NV = 0x20A4;
/*
Accepted by the <piAttribList> parameter of wglCreatePbufferARB and
by the <iAttribute> parameter of wglQueryPbufferARB:
*/
private static final int WGL_DEPTH_TEXTURE_FORMAT_NV = 0x20A5;
/*
Accepted by the <piAttribList> parameter of wglCreatePbufferARB and
by the <iAttribute> parameter of wglQueryPbufferARB:
*/
private static final int WGL_DEPTH_TEXTURE_FORMAT_NV = 0x20A5;
/*
Accepted as a value in the <piAttribList> parameter of wglCreatePbufferARB
and returned in the value parameter of wglQueryPbufferARB when
<iAttribute> is WGL_DEPTH_TEXTURE_FORMAT_NV:
*/
private static final int WGL_TEXTURE_DEPTH_COMPONENT_NV = 0x20A6;
/*
Accepted as a value in the <piAttribList> parameter of wglCreatePbufferARB
and returned in the value parameter of wglQueryPbufferARB when
<iAttribute> is WGL_DEPTH_TEXTURE_FORMAT_NV:
*/
private static final int WGL_TEXTURE_DEPTH_COMPONENT_NV = 0x20A6;
/*
Accepted by the <iBuffer> parameter of wglBindTexImageARB:
*/
static final int WGL_DEPTH_COMPONENT_NV = 0x20A7;
/*
Accepted by the <iBuffer> parameter of wglBindTexImageARB:
*/
static final int WGL_DEPTH_COMPONENT_NV = 0x20A7;
/** The TEXTURE_1D target. */
public static final int RENDER_TEXTURE_1D = WGL_TEXTURE_1D_ARB;
/** The TEXTURE_1D target. */
public static final int RENDER_TEXTURE_1D = WGL_TEXTURE_1D_ARB;
/** The TEXTURE_2D target. */
public static final int RENDER_TEXTURE_2D = WGL_TEXTURE_2D_ARB;
/** The TEXTURE_2D target. */
public static final int RENDER_TEXTURE_2D = WGL_TEXTURE_2D_ARB;
/** The TEXTURE_RECTANGLE target. */
public static final int RENDER_TEXTURE_RECTANGLE = WGL_TEXTURE_RECTANGLE_NV;
/** The TEXTURE_RECTANGLE target. */
public static final int RENDER_TEXTURE_RECTANGLE = WGL_TEXTURE_RECTANGLE_NV;
/** The TEXTURE_CUBE_MAP target. */
public static final int RENDER_TEXTURE_CUBE_MAP = WGL_TEXTURE_CUBE_MAP_ARB;
/** The TEXTURE_CUBE_MAP target. */
public static final int RENDER_TEXTURE_CUBE_MAP = WGL_TEXTURE_CUBE_MAP_ARB;
IntBuffer pixelFormatCaps;
IntBuffer pBufferAttribs;
IntBuffer pixelFormatCaps;
IntBuffer pBufferAttribs;
/**
* Creates a RenderTexture object for enabling render-to-texture on a P-buffer.
* <p/>
* NOTE: Only one of useRGB and useRGBA can be true at the same time.
* <p/>
* NOTE: useRGB(A) and useDepth can be true at the same time, thus allowing two different render textures.
* <p/>
* NOTE: The target parameter can be one of the following:
* <p/>
* RENDER_TEXTURE_1D RENDER_TEXTURE_2D RENDER_TEXTURE_RECTANGLE RENDER_TEXTURE_CUBE_MAP
*
* @param useRGB - When true the P-buffer can be used as an RGB render texture.
* @param useRGBA - When true the P-buffer can be used as an RGBA render texture.
* @param useDepth - When true the P-buffer can be used as a depth render texture.
* @param isRectangle - When true rectangle textures will be allowed on the P-buffer.
* @param target - The texture target of the render texture.
* @param mipmaps - How many mipmap levels to allocate on the P-buffer.
*/
public RenderTexture(boolean useRGB, boolean useRGBA, boolean useDepth, boolean isRectangle, int target, int mipmaps) {
if ( useRGB && useRGBA )
throw new IllegalArgumentException("A RenderTexture can't be both RGB and RGBA.");
/**
* Creates a RenderTexture object for enabling render-to-texture on a P-buffer.
* <p/>
* NOTE: Only one of useRGB and useRGBA can be true at the same time.
* <p/>
* NOTE: useRGB(A) and useDepth can be true at the same time, thus allowing two different render textures.
* <p/>
* NOTE: The target parameter can be one of the following:
* <p/>
* RENDER_TEXTURE_1D RENDER_TEXTURE_2D RENDER_TEXTURE_RECTANGLE RENDER_TEXTURE_CUBE_MAP
*
* @param useRGB - When true the P-buffer can be used as an RGB render texture.
* @param useRGBA - When true the P-buffer can be used as an RGBA render texture.
* @param useDepth - When true the P-buffer can be used as a depth render texture.
* @param isRectangle - When true rectangle textures will be allowed on the P-buffer.
* @param target - The texture target of the render texture.
* @param mipmaps - How many mipmap levels to allocate on the P-buffer.
*/
public RenderTexture(
boolean useRGB, boolean useRGBA, boolean useDepth, boolean isRectangle, int target, int mipmaps) {
if (useRGB && useRGBA) throw new IllegalArgumentException("A RenderTexture can't be both RGB and RGBA.");
if ( mipmaps < 0 )
throw new IllegalArgumentException("The mipmap levels can't be negative.");
if (mipmaps < 0) throw new IllegalArgumentException("The mipmap levels can't be negative.");
if ( isRectangle && target != RENDER_TEXTURE_RECTANGLE )
throw new IllegalArgumentException("When the RenderTexture is rectangle the target must be RENDER_TEXTURE_RECTANGLE.");
if (isRectangle && target != RENDER_TEXTURE_RECTANGLE)
throw new IllegalArgumentException(
"When the RenderTexture is rectangle the target must be RENDER_TEXTURE_RECTANGLE.");
pixelFormatCaps = BufferUtils.createIntBuffer(4);
pBufferAttribs = BufferUtils.createIntBuffer(8);
pixelFormatCaps = BufferUtils.createIntBuffer(4);
pBufferAttribs = BufferUtils.createIntBuffer(8);
if ( useRGB ) {
pixelFormatCaps.put(isRectangle ? WGL_BIND_TO_TEXTURE_RECTANGLE_RGB_NV : WGL_BIND_TO_TEXTURE_RGB_ARB);
pixelFormatCaps.put(GL_TRUE);
if (useRGB) {
pixelFormatCaps.put(isRectangle ? WGL_BIND_TO_TEXTURE_RECTANGLE_RGB_NV : WGL_BIND_TO_TEXTURE_RGB_ARB);
pixelFormatCaps.put(GL_TRUE);
pBufferAttribs.put(WGL_TEXTURE_FORMAT_ARB);
pBufferAttribs.put(WGL_TEXTURE_RGB_ARB);
} else if ( useRGBA ) {
pixelFormatCaps.put(isRectangle ? WGL_BIND_TO_TEXTURE_RECTANGLE_RGBA_NV : WGL_BIND_TO_TEXTURE_RGBA_ARB);
pixelFormatCaps.put(GL_TRUE);
pBufferAttribs.put(WGL_TEXTURE_FORMAT_ARB);
pBufferAttribs.put(WGL_TEXTURE_RGB_ARB);
} else if (useRGBA) {
pixelFormatCaps.put(isRectangle ? WGL_BIND_TO_TEXTURE_RECTANGLE_RGBA_NV : WGL_BIND_TO_TEXTURE_RGBA_ARB);
pixelFormatCaps.put(GL_TRUE);
pBufferAttribs.put(WGL_TEXTURE_FORMAT_ARB);
pBufferAttribs.put(WGL_TEXTURE_RGBA_ARB);
}
pBufferAttribs.put(WGL_TEXTURE_FORMAT_ARB);
pBufferAttribs.put(WGL_TEXTURE_RGBA_ARB);
}
if ( useDepth ) {
pixelFormatCaps.put(isRectangle ? WGL_BIND_TO_TEXTURE_RECTANGLE_DEPTH_NV : WGL_BIND_TO_TEXTURE_DEPTH_NV);
pixelFormatCaps.put(GL_TRUE);
if (useDepth) {
pixelFormatCaps.put(isRectangle ? WGL_BIND_TO_TEXTURE_RECTANGLE_DEPTH_NV : WGL_BIND_TO_TEXTURE_DEPTH_NV);
pixelFormatCaps.put(GL_TRUE);
pBufferAttribs.put(WGL_DEPTH_TEXTURE_FORMAT_NV);
pBufferAttribs.put(WGL_TEXTURE_DEPTH_COMPONENT_NV);
}
pBufferAttribs.put(WGL_DEPTH_TEXTURE_FORMAT_NV);
pBufferAttribs.put(WGL_TEXTURE_DEPTH_COMPONENT_NV);
}
pBufferAttribs.put(WGL_TEXTURE_TARGET_ARB);
pBufferAttribs.put(target);
pBufferAttribs.put(WGL_TEXTURE_TARGET_ARB);
pBufferAttribs.put(target);
if ( mipmaps != 0 ) {
pBufferAttribs.put(WGL_MIPMAP_TEXTURE_ARB);
pBufferAttribs.put(mipmaps);
}
if (mipmaps != 0) {
pBufferAttribs.put(WGL_MIPMAP_TEXTURE_ARB);
pBufferAttribs.put(mipmaps);
}
pixelFormatCaps.flip();
pBufferAttribs.flip();
}
}
pixelFormatCaps.flip();
pBufferAttribs.flip();
}
}
+131 -130
View File
@@ -34,142 +34,143 @@ package org.lwjglx.opengl;
import org.lwjglx.Sys;
/**
* A highly accurate sync method that continually adapts to the system
* it runs on to provide reliable results.
*
* @author Riven
* @author kappaOne
*/
* A highly accurate sync method that continually adapts to the system
* it runs on to provide reliable results.
*
* @author Riven
* @author kappaOne
*/
class Sync {
/** number of nano seconds in a second */
private static final long NANOS_IN_SECOND = 1000L * 1000L * 1000L;
/** number of nano seconds in a second */
private static final long NANOS_IN_SECOND = 1000L * 1000L * 1000L;
/** The time to sleep/yield until the next frame */
private static long nextFrame = 0;
/** whether the initialisation code has run */
private static boolean initialised = false;
/** for calculating the averages the previous sleep/yield times are stored */
private static RunningAvg sleepDurations = new RunningAvg(10);
private static RunningAvg yieldDurations = new RunningAvg(10);
/**
* An accurate sync method that will attempt to run at a constant frame rate.
* It should be called once every frame.
*
* @param fps - the desired frame rate, in frames per second
*/
public static void sync(int fps) {
if (fps <= 0) return;
if (!initialised) initialise();
try {
// sleep until the average sleep time is greater than the time remaining till nextFrame
for (long t0 = getTime(), t1; (nextFrame - t0) > sleepDurations.avg(); t0 = t1) {
Thread.sleep(1);
sleepDurations.add((t1 = getTime()) - t0); // update average sleep time
}
// slowly dampen sleep average if too high to avoid yielding too much
sleepDurations.dampenForLowResTicker();
// yield until the average yield time is greater than the time remaining till nextFrame
for (long t0 = getTime(), t1; (nextFrame - t0) > yieldDurations.avg(); t0 = t1) {
Thread.yield();
yieldDurations.add((t1 = getTime()) - t0); // update average yield time
}
} catch (InterruptedException e) {
}
// schedule next frame, drop frame(s) if already too late for next frame
nextFrame = Math.max(nextFrame + NANOS_IN_SECOND / fps, getTime());
}
/**
* This method will initialise the sync method by setting initial
* values for sleepDurations/yieldDurations and nextFrame.
*
* If running on windows it will start the sleep timer fix.
*/
private static void initialise() {
initialised = true;
sleepDurations.init(1000 * 1000);
yieldDurations.init((int) (-(getTime() - getTime()) * 1.333));
nextFrame = getTime();
String osName = System.getProperty("os.name");
if (osName.startsWith("Win")) {
// On windows the sleep functions can be highly inaccurate by
// over 10ms making in unusable. However it can be forced to
// be a bit more accurate by running a separate sleeping daemon
// thread.
Thread timerAccuracyThread = new Thread(new Runnable() {
public void run() {
try {
Thread.sleep(Long.MAX_VALUE);
} catch (Exception e) {}
}
});
timerAccuracyThread.setName("LWJGL Timer");
timerAccuracyThread.setDaemon(true);
timerAccuracyThread.start();
}
}
/** The time to sleep/yield until the next frame */
private static long nextFrame = 0;
/**
* Get the system time in nano seconds
*
* @return will return the current time in nano's
*/
private static long getTime() {
return (Sys.getTime() * NANOS_IN_SECOND) / Sys.getTimerResolution();
}
/** whether the initialisation code has run */
private static boolean initialised = false;
private static class RunningAvg {
private final long[] slots;
private int offset;
private static final long DAMPEN_THRESHOLD = 10 * 1000L * 1000L; // 10ms
private static final float DAMPEN_FACTOR = 0.9f; // don't change: 0.9f is exactly right!
/** for calculating the averages the previous sleep/yield times are stored */
private static RunningAvg sleepDurations = new RunningAvg(10);
public RunningAvg(int slotCount) {
this.slots = new long[slotCount];
this.offset = 0;
}
private static RunningAvg yieldDurations = new RunningAvg(10);
public void init(long value) {
while (this.offset < this.slots.length) {
this.slots[this.offset++] = value;
}
}
/**
* An accurate sync method that will attempt to run at a constant frame rate.
* It should be called once every frame.
*
* @param fps - the desired frame rate, in frames per second
*/
public static void sync(int fps) {
if (fps <= 0) return;
if (!initialised) initialise();
public void add(long value) {
this.slots[this.offset++ % this.slots.length] = value;
this.offset %= this.slots.length;
}
try {
// sleep until the average sleep time is greater than the time remaining till nextFrame
for (long t0 = getTime(), t1; (nextFrame - t0) > sleepDurations.avg(); t0 = t1) {
Thread.sleep(1);
sleepDurations.add((t1 = getTime()) - t0); // update average sleep time
}
public long avg() {
long sum = 0;
for (int i = 0; i < this.slots.length; i++) {
sum += this.slots[i];
}
return sum / this.slots.length;
}
public void dampenForLowResTicker() {
if (this.avg() > DAMPEN_THRESHOLD) {
for (int i = 0; i < this.slots.length; i++) {
this.slots[i] *= DAMPEN_FACTOR;
}
}
}
}
}
// slowly dampen sleep average if too high to avoid yielding too much
sleepDurations.dampenForLowResTicker();
// yield until the average yield time is greater than the time remaining till nextFrame
for (long t0 = getTime(), t1; (nextFrame - t0) > yieldDurations.avg(); t0 = t1) {
Thread.yield();
yieldDurations.add((t1 = getTime()) - t0); // update average yield time
}
} catch (InterruptedException e) {
}
// schedule next frame, drop frame(s) if already too late for next frame
nextFrame = Math.max(nextFrame + NANOS_IN_SECOND / fps, getTime());
}
/**
* This method will initialise the sync method by setting initial
* values for sleepDurations/yieldDurations and nextFrame.
*
* If running on windows it will start the sleep timer fix.
*/
private static void initialise() {
initialised = true;
sleepDurations.init(1000 * 1000);
yieldDurations.init((int) (-(getTime() - getTime()) * 1.333));
nextFrame = getTime();
String osName = System.getProperty("os.name");
if (osName.startsWith("Win")) {
// On windows the sleep functions can be highly inaccurate by
// over 10ms making in unusable. However it can be forced to
// be a bit more accurate by running a separate sleeping daemon
// thread.
Thread timerAccuracyThread = new Thread(new Runnable() {
public void run() {
try {
Thread.sleep(Long.MAX_VALUE);
} catch (Exception e) {
}
}
});
timerAccuracyThread.setName("LWJGL Timer");
timerAccuracyThread.setDaemon(true);
timerAccuracyThread.start();
}
}
/**
* Get the system time in nano seconds
*
* @return will return the current time in nano's
*/
private static long getTime() {
return (Sys.getTime() * NANOS_IN_SECOND) / Sys.getTimerResolution();
}
private static class RunningAvg {
private final long[] slots;
private int offset;
private static final long DAMPEN_THRESHOLD = 10 * 1000L * 1000L; // 10ms
private static final float DAMPEN_FACTOR = 0.9f; // don't change: 0.9f is exactly right!
public RunningAvg(int slotCount) {
this.slots = new long[slotCount];
this.offset = 0;
}
public void init(long value) {
while (this.offset < this.slots.length) {
this.slots[this.offset++] = value;
}
}
public void add(long value) {
this.slots[this.offset++ % this.slots.length] = value;
this.offset %= this.slots.length;
}
public long avg() {
long sum = 0;
for (int i = 0; i < this.slots.length; i++) {
sum += this.slots[i];
}
return sum / this.slots.length;
}
public void dampenForLowResTicker() {
if (this.avg() > DAMPEN_THRESHOLD) {
for (int i = 0; i < this.slots.length; i++) {
this.slots[i] *= DAMPEN_FACTOR;
}
}
}
}
}
+39 -41
View File
@@ -43,48 +43,46 @@ import org.lwjgl.opengl.GLContext;
* @author cix_foo <[email protected]>
* @version $Revision$
*/
public final class Util {
static org.lwjgl.opengl.GLContext glContext = GLContext.createFromCurrent();
/** No c'tor */
private Util() {
}
/**
* Throws OpenGLException if glGetError() returns anything else than GL_NO_ERROR
*
*/
public static void checkGLError() throws OpenGLException {
glContext.checkGLError();
}
static org.lwjgl.opengl.GLContext glContext = GLContext.createFromCurrent();
/**
* Translate a GL error code to a String describing the error
*/
public static String translateGLErrorString(int error_code) {
switch (error_code) {
case GL_NO_ERROR:
return "No error";
case GL_INVALID_ENUM:
return "Invalid enum";
case GL_INVALID_VALUE:
return "Invalid value";
case GL_INVALID_OPERATION:
return "Invalid operation";
case GL_STACK_OVERFLOW:
return "Stack overflow";
case GL_STACK_UNDERFLOW:
return "Stack underflow";
case GL_OUT_OF_MEMORY:
return "Out of memory";
case GL_TABLE_TOO_LARGE:
return "Table too large";
case GL_INVALID_FRAMEBUFFER_OPERATION:
return "Invalid framebuffer operation";
default:
return null;
}
}
/** No c'tor */
private Util() {}
/**
* Throws OpenGLException if glGetError() returns anything else than GL_NO_ERROR
*
*/
public static void checkGLError() throws OpenGLException {
glContext.checkGLError();
}
/**
* Translate a GL error code to a String describing the error
*/
public static String translateGLErrorString(int error_code) {
switch (error_code) {
case GL_NO_ERROR:
return "No error";
case GL_INVALID_ENUM:
return "Invalid enum";
case GL_INVALID_VALUE:
return "Invalid value";
case GL_INVALID_OPERATION:
return "Invalid operation";
case GL_STACK_OVERFLOW:
return "Stack overflow";
case GL_STACK_UNDERFLOW:
return "Stack underflow";
case GL_OUT_OF_MEMORY:
return "Out of memory";
case GL_TABLE_TOO_LARGE:
return "Table too large";
case GL_INVALID_FRAMEBUFFER_OPERATION:
return "Invalid framebuffer operation";
default:
return null;
}
}
}
+246 -243
View File
@@ -35,8 +35,10 @@
*/
package org.lwjglx.test.opengl;
import java.nio.FloatBuffer;
import static org.lwjgl.opengl.ARBTransposeMatrix.*;
import static org.lwjgl.opengl.GL11.*;
import java.nio.FloatBuffer;
import org.lwjglx.BufferUtils;
import org.lwjglx.LWJGLException;
import org.lwjglx.LWJGLUtil;
@@ -45,9 +47,6 @@ import org.lwjglx.opengl.Display;
import org.lwjglx.opengl.DisplayMode;
import org.lwjglx.opengl.GLContext;
import static org.lwjgl.opengl.ARBTransposeMatrix.*;
import static org.lwjgl.opengl.GL11.*;
/**
* <p>
* This is the OpenGL "standard" Gears demo, originally by Brian Paul
@@ -58,286 +57,290 @@ import static org.lwjgl.opengl.GL11.*;
*/
public class Gears {
private float view_rotx = 20.0f;
private float view_rotx = 20.0f;
private float view_roty = 30.0f;
private float view_roty = 30.0f;
private float view_rotz;
private float view_rotz;
private int gear1;
private int gear1;
private int gear2;
private int gear2;
private int gear3;
private int gear3;
private float angle;
private float angle;
public static void main(String[] args) {
new Gears().execute();
System.exit(0);
}
public static void main(String[] args) {
new Gears().execute();
System.exit(0);
}
/**
*
*/
private void execute() {
try {
init();
} catch (LWJGLException le) {
le.printStackTrace();
System.out.println("Failed to initialize Gears.");
return;
}
/**
*
*/
private void execute() {
try {
init();
} catch (LWJGLException le) {
le.printStackTrace();
System.out.println("Failed to initialize Gears.");
return;
}
loop();
loop();
destroy();
}
destroy();
}
/**
*
*/
private void destroy() {
Display.destroy();
}
/**
*
*/
private void destroy() {
Display.destroy();
}
/**
*
*/
private void loop() {
long startTime = System.currentTimeMillis() + 5000;
long fps = 0;
/**
*
*/
private void loop() {
long startTime = System.currentTimeMillis() + 5000;
long fps = 0;
while (!Display.isCloseRequested()) {
angle += 2.0f;
while (!Display.isCloseRequested()) {
angle += 2.0f;
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glPushMatrix();
glRotatef(view_rotx, 1.0f, 0.0f, 0.0f);
glRotatef(view_roty, 0.0f, 1.0f, 0.0f);
glRotatef(view_rotz, 0.0f, 0.0f, 1.0f);
glPushMatrix();
glRotatef(view_rotx, 1.0f, 0.0f, 0.0f);
glRotatef(view_roty, 0.0f, 1.0f, 0.0f);
glRotatef(view_rotz, 0.0f, 0.0f, 1.0f);
glPushMatrix();
glTranslatef(-3.0f, -2.0f, 0.0f);
glRotatef(angle, 0.0f, 0.0f, 1.0f);
glCallList(gear1);
glPopMatrix();
glPushMatrix();
glTranslatef(-3.0f, -2.0f, 0.0f);
glRotatef(angle, 0.0f, 0.0f, 1.0f);
glCallList(gear1);
glPopMatrix();
glPushMatrix();
glTranslatef(3.1f, -2.0f, 0.0f);
glRotatef(-2.0f * angle - 9.0f, 0.0f, 0.0f, 1.0f);
glCallList(gear2);
glPopMatrix();
glPushMatrix();
glTranslatef(3.1f, -2.0f, 0.0f);
glRotatef(-2.0f * angle - 9.0f, 0.0f, 0.0f, 1.0f);
glCallList(gear2);
glPopMatrix();
glPushMatrix();
glTranslatef(-3.1f, 4.2f, 0.0f);
glRotatef(-2.0f * angle - 25.0f, 0.0f, 0.0f, 1.0f);
glCallList(gear3);
glPopMatrix();
glPushMatrix();
glTranslatef(-3.1f, 4.2f, 0.0f);
glRotatef(-2.0f * angle - 25.0f, 0.0f, 0.0f, 1.0f);
glCallList(gear3);
glPopMatrix();
glPopMatrix();
glPopMatrix();
Display.update();
if (startTime > System.currentTimeMillis()) {
fps++;
} else {
long timeUsed = 5000 + (startTime - System.currentTimeMillis());
startTime = System.currentTimeMillis() + 5000;
System.out.println(fps + " frames in " + timeUsed / 1000f + " seconds = "
+ (fps / (timeUsed / 1000f)));
fps = 0;
}
}
}
Display.update();
if (startTime > System.currentTimeMillis()) {
fps++;
} else {
long timeUsed = 5000 + (startTime - System.currentTimeMillis());
startTime = System.currentTimeMillis() + 5000;
System.out.println(fps + " frames in " + timeUsed / 1000f + " seconds = " + (fps / (timeUsed / 1000f)));
fps = 0;
}
}
}
/**
*
*/
private void init() throws LWJGLException {
// create Window of size 300x300
Display.setLocation((Display.getDisplayMode().getWidth() - 300) / 2,
(Display.getDisplayMode().getHeight() - 300) / 2);
Display.setDisplayMode(new DisplayMode(300, 300));
Display.setTitle("Gears");
Display.create();
/**
*
*/
private void init() throws LWJGLException {
// create Window of size 300x300
Display.setLocation(
(Display.getDisplayMode().getWidth() - 300) / 2,
(Display.getDisplayMode().getHeight() - 300) / 2);
Display.setDisplayMode(new DisplayMode(300, 300));
Display.setTitle("Gears");
Display.create();
// setup ogl
FloatBuffer pos = BufferUtils.createFloatBuffer(4).put(new float[] { 5.0f, 5.0f, 10.0f, 0.0f});
FloatBuffer red = BufferUtils.createFloatBuffer(4).put(new float[] { 0.8f, 0.1f, 0.0f, 1.0f});
FloatBuffer green = BufferUtils.createFloatBuffer(4).put(new float[] { 0.0f, 0.8f, 0.2f, 1.0f});
FloatBuffer blue = BufferUtils.createFloatBuffer(4).put(new float[] { 0.2f, 0.2f, 1.0f, 1.0f});
// setup ogl
FloatBuffer pos = BufferUtils.createFloatBuffer(4).put(new float[] {5.0f, 5.0f, 10.0f, 0.0f});
FloatBuffer red = BufferUtils.createFloatBuffer(4).put(new float[] {0.8f, 0.1f, 0.0f, 1.0f});
FloatBuffer green = BufferUtils.createFloatBuffer(4).put(new float[] {0.0f, 0.8f, 0.2f, 1.0f});
FloatBuffer blue = BufferUtils.createFloatBuffer(4).put(new float[] {0.2f, 0.2f, 1.0f, 1.0f});
pos.flip();
red.flip();
green.flip();
blue.flip();
pos.flip();
red.flip();
green.flip();
blue.flip();
glLight(GL_LIGHT0, GL_POSITION, pos);
glEnable(GL_CULL_FACE);
glEnable(GL_LIGHTING);
glEnable(GL_LIGHT0);
glEnable(GL_DEPTH_TEST);
glLight(GL_LIGHT0, GL_POSITION, pos);
glEnable(GL_CULL_FACE);
glEnable(GL_LIGHTING);
glEnable(GL_LIGHT0);
glEnable(GL_DEPTH_TEST);
/* make the gears */
gear1 = glGenLists(1);
glNewList(gear1, GL_COMPILE);
glMaterial(GL_FRONT, GL_AMBIENT_AND_DIFFUSE, red);
gear(1.0f, 4.0f, 1.0f, 20, 0.7f);
glEndList();
/* make the gears */
gear1 = glGenLists(1);
glNewList(gear1, GL_COMPILE);
glMaterial(GL_FRONT, GL_AMBIENT_AND_DIFFUSE, red);
gear(1.0f, 4.0f, 1.0f, 20, 0.7f);
glEndList();
gear2 = glGenLists(1);
glNewList(gear2, GL_COMPILE);
glMaterial(GL_FRONT, GL_AMBIENT_AND_DIFFUSE, green);
gear(0.5f, 2.0f, 2.0f, 10, 0.7f);
glEndList();
gear2 = glGenLists(1);
glNewList(gear2, GL_COMPILE);
glMaterial(GL_FRONT, GL_AMBIENT_AND_DIFFUSE, green);
gear(0.5f, 2.0f, 2.0f, 10, 0.7f);
glEndList();
gear3 = glGenLists(1);
glNewList(gear3, GL_COMPILE);
glMaterial(GL_FRONT, GL_AMBIENT_AND_DIFFUSE, blue);
gear(1.3f, 2.0f, 0.5f, 10, 0.7f);
glEndList();
gear3 = glGenLists(1);
glNewList(gear3, GL_COMPILE);
glMaterial(GL_FRONT, GL_AMBIENT_AND_DIFFUSE, blue);
gear(1.3f, 2.0f, 0.5f, 10, 0.7f);
glEndList();
glEnable(GL_NORMALIZE);
glEnable(GL_NORMALIZE);
glMatrixMode(GL_PROJECTION);
glMatrixMode(GL_PROJECTION);
System.err.println("LWJGL: " + Sys.getVersion() + " / " + LWJGLUtil.getPlatformName());
System.err.println("GL_VENDOR: " + glGetString(GL_VENDOR));
System.err.println("GL_RENDERER: " + glGetString(GL_RENDERER));
System.err.println("GL_VERSION: " + glGetString(GL_VERSION));
System.err.println();
System.err.println("glLoadTransposeMatrixfARB() supported: " + GLContext.getCapabilities().GL_ARB_transpose_matrix);
if (!GLContext.getCapabilities().GL_ARB_transpose_matrix) {
// --- not using extensions
glLoadIdentity();
} else {
// --- using extensions
final FloatBuffer identityTranspose = BufferUtils.createFloatBuffer(16).put(
new float[] { 1, 0, 0, 0, 0, 1, 0, 0,
0, 0, 1, 0, 0, 0, 0, 1});
identityTranspose.flip();
glLoadTransposeMatrixARB(identityTranspose);
}
System.err.println("LWJGL: " + Sys.getVersion() + " / " + LWJGLUtil.getPlatformName());
System.err.println("GL_VENDOR: " + glGetString(GL_VENDOR));
System.err.println("GL_RENDERER: " + glGetString(GL_RENDERER));
System.err.println("GL_VERSION: " + glGetString(GL_VERSION));
System.err.println();
System.err.println(
"glLoadTransposeMatrixfARB() supported: " + GLContext.getCapabilities().GL_ARB_transpose_matrix);
if (!GLContext.getCapabilities().GL_ARB_transpose_matrix) {
// --- not using extensions
glLoadIdentity();
} else {
// --- using extensions
final FloatBuffer identityTranspose =
BufferUtils.createFloatBuffer(16).put(new float[] {1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1});
identityTranspose.flip();
glLoadTransposeMatrixARB(identityTranspose);
}
float h = (float) 300 / (float) 300;
glFrustum(-1.0f, 1.0f, -h, h, 5.0f, 60.0f);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
glTranslatef(0.0f, 0.0f, -40.0f);
}
float h = (float) 300 / (float) 300;
glFrustum(-1.0f, 1.0f, -h, h, 5.0f, 60.0f);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
glTranslatef(0.0f, 0.0f, -40.0f);
}
/**
* Draw a gear wheel. You'll probably want to call this function when
* building a display list since we do a lot of trig here.
*
* @param inner_radius radius of hole at center
* @param outer_radius radius at center of teeth
* @param width width of gear
* @param teeth number of teeth
* @param tooth_depth depth of tooth
*/
private void gear(float inner_radius, float outer_radius, float width, int teeth, float tooth_depth) {
int i;
float r0, r1, r2;
float angle, da;
float u, v, len;
/**
* Draw a gear wheel. You'll probably want to call this function when
* building a display list since we do a lot of trig here.
*
* @param inner_radius radius of hole at center
* @param outer_radius radius at center of teeth
* @param width width of gear
* @param teeth number of teeth
* @param tooth_depth depth of tooth
*/
private void gear(float inner_radius, float outer_radius, float width, int teeth, float tooth_depth) {
int i;
float r0, r1, r2;
float angle, da;
float u, v, len;
r0 = inner_radius;
r1 = outer_radius - tooth_depth / 2.0f;
r2 = outer_radius + tooth_depth / 2.0f;
r0 = inner_radius;
r1 = outer_radius - tooth_depth / 2.0f;
r2 = outer_radius + tooth_depth / 2.0f;
da = 2.0f * (float) Math.PI / teeth / 4.0f;
da = 2.0f * (float) Math.PI / teeth / 4.0f;
glShadeModel(GL_FLAT);
glShadeModel(GL_FLAT);
glNormal3f(0.0f, 0.0f, 1.0f);
glNormal3f(0.0f, 0.0f, 1.0f);
/* draw front face */
glBegin(GL_QUAD_STRIP);
for (i = 0; i <= teeth; i++) {
angle = i * 2.0f * (float) Math.PI / teeth;
glVertex3f(r0 * (float) Math.cos(angle), r0 * (float) Math.sin(angle), width * 0.5f);
glVertex3f(r1 * (float) Math.cos(angle), r1 * (float) Math.sin(angle), width * 0.5f);
if (i < teeth) {
glVertex3f(r0 * (float) Math.cos(angle), r0 * (float) Math.sin(angle), width * 0.5f);
glVertex3f(r1 * (float) Math.cos(angle + 3.0f * da), r1 * (float) Math.sin(angle + 3.0f * da),
width * 0.5f);
}
}
glEnd();
/* draw front face */
glBegin(GL_QUAD_STRIP);
for (i = 0; i <= teeth; i++) {
angle = i * 2.0f * (float) Math.PI / teeth;
glVertex3f(r0 * (float) Math.cos(angle), r0 * (float) Math.sin(angle), width * 0.5f);
glVertex3f(r1 * (float) Math.cos(angle), r1 * (float) Math.sin(angle), width * 0.5f);
if (i < teeth) {
glVertex3f(r0 * (float) Math.cos(angle), r0 * (float) Math.sin(angle), width * 0.5f);
glVertex3f(
r1 * (float) Math.cos(angle + 3.0f * da),
r1 * (float) Math.sin(angle + 3.0f * da),
width * 0.5f);
}
}
glEnd();
/* draw front sides of teeth */
glBegin(GL_QUADS);
for (i = 0; i < teeth; i++) {
angle = i * 2.0f * (float) Math.PI / teeth;
glVertex3f(r1 * (float) Math.cos(angle), r1 * (float) Math.sin(angle), width * 0.5f);
glVertex3f(r2 * (float) Math.cos(angle + da), r2 * (float) Math.sin(angle + da), width * 0.5f);
glVertex3f(r2 * (float) Math.cos(angle + 2.0f * da), r2 * (float) Math.sin(angle + 2.0f * da), width * 0.5f);
glVertex3f(r1 * (float) Math.cos(angle + 3.0f * da), r1 * (float) Math.sin(angle + 3.0f * da), width * 0.5f);
}
glEnd();
/* draw front sides of teeth */
glBegin(GL_QUADS);
for (i = 0; i < teeth; i++) {
angle = i * 2.0f * (float) Math.PI / teeth;
glVertex3f(r1 * (float) Math.cos(angle), r1 * (float) Math.sin(angle), width * 0.5f);
glVertex3f(r2 * (float) Math.cos(angle + da), r2 * (float) Math.sin(angle + da), width * 0.5f);
glVertex3f(
r2 * (float) Math.cos(angle + 2.0f * da), r2 * (float) Math.sin(angle + 2.0f * da), width * 0.5f);
glVertex3f(
r1 * (float) Math.cos(angle + 3.0f * da), r1 * (float) Math.sin(angle + 3.0f * da), width * 0.5f);
}
glEnd();
/* draw back face */
glBegin(GL_QUAD_STRIP);
for (i = 0; i <= teeth; i++) {
angle = i * 2.0f * (float) Math.PI / teeth;
glVertex3f(r1 * (float) Math.cos(angle), r1 * (float) Math.sin(angle), -width * 0.5f);
glVertex3f(r0 * (float) Math.cos(angle), r0 * (float) Math.sin(angle), -width * 0.5f);
glVertex3f(r1 * (float) Math.cos(angle + 3 * da), r1 * (float) Math.sin(angle + 3 * da), -width * 0.5f);
glVertex3f(r0 * (float) Math.cos(angle), r0 * (float) Math.sin(angle), -width * 0.5f);
}
glEnd();
/* draw back face */
glBegin(GL_QUAD_STRIP);
for (i = 0; i <= teeth; i++) {
angle = i * 2.0f * (float) Math.PI / teeth;
glVertex3f(r1 * (float) Math.cos(angle), r1 * (float) Math.sin(angle), -width * 0.5f);
glVertex3f(r0 * (float) Math.cos(angle), r0 * (float) Math.sin(angle), -width * 0.5f);
glVertex3f(r1 * (float) Math.cos(angle + 3 * da), r1 * (float) Math.sin(angle + 3 * da), -width * 0.5f);
glVertex3f(r0 * (float) Math.cos(angle), r0 * (float) Math.sin(angle), -width * 0.5f);
}
glEnd();
/* draw back sides of teeth */
glBegin(GL_QUADS);
for (i = 0; i < teeth; i++) {
angle = i * 2.0f * (float) Math.PI / teeth;
glVertex3f(r1 * (float) Math.cos(angle + 3 * da), r1 * (float) Math.sin(angle + 3 * da), -width * 0.5f);
glVertex3f(r2 * (float) Math.cos(angle + 2 * da), r2 * (float) Math.sin(angle + 2 * da), -width * 0.5f);
glVertex3f(r2 * (float) Math.cos(angle + da), r2 * (float) Math.sin(angle + da), -width * 0.5f);
glVertex3f(r1 * (float) Math.cos(angle), r1 * (float) Math.sin(angle), -width * 0.5f);
}
glEnd();
/* draw back sides of teeth */
glBegin(GL_QUADS);
for (i = 0; i < teeth; i++) {
angle = i * 2.0f * (float) Math.PI / teeth;
glVertex3f(r1 * (float) Math.cos(angle + 3 * da), r1 * (float) Math.sin(angle + 3 * da), -width * 0.5f);
glVertex3f(r2 * (float) Math.cos(angle + 2 * da), r2 * (float) Math.sin(angle + 2 * da), -width * 0.5f);
glVertex3f(r2 * (float) Math.cos(angle + da), r2 * (float) Math.sin(angle + da), -width * 0.5f);
glVertex3f(r1 * (float) Math.cos(angle), r1 * (float) Math.sin(angle), -width * 0.5f);
}
glEnd();
/* draw outward faces of teeth */
glBegin(GL_QUAD_STRIP);
for (i = 0; i < teeth; i++) {
angle = i * 2.0f * (float) Math.PI / teeth;
glVertex3f(r1 * (float) Math.cos(angle), r1 * (float) Math.sin(angle), width * 0.5f);
glVertex3f(r1 * (float) Math.cos(angle), r1 * (float) Math.sin(angle), -width * 0.5f);
u = r2 * (float) Math.cos(angle + da) - r1 * (float) Math.cos(angle);
v = r2 * (float) Math.sin(angle + da) - r1 * (float) Math.sin(angle);
len = (float) Math.sqrt(u * u + v * v);
u /= len;
v /= len;
glNormal3f(v, -u, 0.0f);
glVertex3f(r2 * (float) Math.cos(angle + da), r2 * (float) Math.sin(angle + da), width * 0.5f);
glVertex3f(r2 * (float) Math.cos(angle + da), r2 * (float) Math.sin(angle + da), -width * 0.5f);
glNormal3f((float) Math.cos(angle), (float) Math.sin(angle), 0.0f);
glVertex3f(r2 * (float) Math.cos(angle + 2 * da), r2 * (float) Math.sin(angle + 2 * da), width * 0.5f);
glVertex3f(r2 * (float) Math.cos(angle + 2 * da), r2 * (float) Math.sin(angle + 2 * da), -width * 0.5f);
u = r1 * (float) Math.cos(angle + 3 * da) - r2 * (float) Math.cos(angle + 2 * da);
v = r1 * (float) Math.sin(angle + 3 * da) - r2 * (float) Math.sin(angle + 2 * da);
glNormal3f(v, -u, 0.0f);
glVertex3f(r1 * (float) Math.cos(angle + 3 * da), r1 * (float) Math.sin(angle + 3 * da), width * 0.5f);
glVertex3f(r1 * (float) Math.cos(angle + 3 * da), r1 * (float) Math.sin(angle + 3 * da), -width * 0.5f);
glNormal3f((float) Math.cos(angle), (float) Math.sin(angle), 0.0f);
}
glVertex3f(r1 * (float) Math.cos(0), r1 * (float) Math.sin(0), width * 0.5f);
glVertex3f(r1 * (float) Math.cos(0), r1 * (float) Math.sin(0), -width * 0.5f);
glEnd();
/* draw outward faces of teeth */
glBegin(GL_QUAD_STRIP);
for (i = 0; i < teeth; i++) {
angle = i * 2.0f * (float) Math.PI / teeth;
glVertex3f(r1 * (float) Math.cos(angle), r1 * (float) Math.sin(angle), width * 0.5f);
glVertex3f(r1 * (float) Math.cos(angle), r1 * (float) Math.sin(angle), -width * 0.5f);
u = r2 * (float) Math.cos(angle + da) - r1 * (float) Math.cos(angle);
v = r2 * (float) Math.sin(angle + da) - r1 * (float) Math.sin(angle);
len = (float) Math.sqrt(u * u + v * v);
u /= len;
v /= len;
glNormal3f(v, -u, 0.0f);
glVertex3f(r2 * (float) Math.cos(angle + da), r2 * (float) Math.sin(angle + da), width * 0.5f);
glVertex3f(r2 * (float) Math.cos(angle + da), r2 * (float) Math.sin(angle + da), -width * 0.5f);
glNormal3f((float) Math.cos(angle), (float) Math.sin(angle), 0.0f);
glVertex3f(r2 * (float) Math.cos(angle + 2 * da), r2 * (float) Math.sin(angle + 2 * da), width * 0.5f);
glVertex3f(r2 * (float) Math.cos(angle + 2 * da), r2 * (float) Math.sin(angle + 2 * da), -width * 0.5f);
u = r1 * (float) Math.cos(angle + 3 * da) - r2 * (float) Math.cos(angle + 2 * da);
v = r1 * (float) Math.sin(angle + 3 * da) - r2 * (float) Math.sin(angle + 2 * da);
glNormal3f(v, -u, 0.0f);
glVertex3f(r1 * (float) Math.cos(angle + 3 * da), r1 * (float) Math.sin(angle + 3 * da), width * 0.5f);
glVertex3f(r1 * (float) Math.cos(angle + 3 * da), r1 * (float) Math.sin(angle + 3 * da), -width * 0.5f);
glNormal3f((float) Math.cos(angle), (float) Math.sin(angle), 0.0f);
}
glVertex3f(r1 * (float) Math.cos(0), r1 * (float) Math.sin(0), width * 0.5f);
glVertex3f(r1 * (float) Math.cos(0), r1 * (float) Math.sin(0), -width * 0.5f);
glEnd();
glShadeModel(GL_SMOOTH);
glShadeModel(GL_SMOOTH);
/* draw inside radius cylinder */
glBegin(GL_QUAD_STRIP);
for (i = 0; i <= teeth; i++) {
angle = i * 2.0f * (float) Math.PI / teeth;
glNormal3f(-(float) Math.cos(angle), -(float) Math.sin(angle), 0.0f);
glVertex3f(r0 * (float) Math.cos(angle), r0 * (float) Math.sin(angle), -width * 0.5f);
glVertex3f(r0 * (float) Math.cos(angle), r0 * (float) Math.sin(angle), width * 0.5f);
}
glEnd();
}
/* draw inside radius cylinder */
glBegin(GL_QUAD_STRIP);
for (i = 0; i <= teeth; i++) {
angle = i * 2.0f * (float) Math.PI / teeth;
glNormal3f(-(float) Math.cos(angle), -(float) Math.sin(angle), 0.0f);
glVertex3f(r0 * (float) Math.cos(angle), r0 * (float) Math.sin(angle), -width * 0.5f);
glVertex3f(r0 * (float) Math.cos(angle), r0 * (float) Math.sin(angle), width * 0.5f);
}
glEnd();
}
}
@@ -1,31 +1,31 @@
/*
/*
* Copyright (c) 2002-2008 LWJGL Project
* All rights reserved.
*
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* * Neither the name of 'LWJGL' nor the names of
* its contributors may be used to endorse or promote products derived
* * Neither the name of 'LWJGL' nor the names of
* its contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
@@ -33,125 +33,125 @@ package org.lwjglx.test.spaceinvaders;
/**
* An entity which represents one of our space invader aliens.
*
*
* @author Kevin Glass
* @author Brian Matzon
*/
public class AlienEntity extends Entity {
/** Movement made downwards when a border is hit */
private static final int DOWNWARD_MOVEMENT = 10;
/** Movement made downwards when a border is hit */
private static final int DOWNWARD_MOVEMENT = 10;
/** Border at which player dies */
private static final int BOTTOM_BORDER = 570;
/** Border at which player dies */
private static final int BOTTOM_BORDER = 570;
/** Right border at which to shift direction */
private static final int RIGHT_BORDER = 750;
/** Right border at which to shift direction */
private static final int RIGHT_BORDER = 750;
/** Left border at which to shift direction */
private static final int LEFT_BORDER = 10;
/** Left border at which to shift direction */
private static final int LEFT_BORDER = 10;
/** The speed at which the alient moves horizontally */
private float moveSpeed = 75;
/** The speed at which the alient moves horizontally */
private float moveSpeed = 75;
/** The game in which the entity exists */
private Game game;
/** The game in which the entity exists */
private Game game;
/** The animation frames */
private Sprite[] frames = new Sprite[4];
/** The animation frames */
private Sprite[] frames = new Sprite[4];
/** The time since the last frame change took place */
private long lastFrameChange;
/** The time since the last frame change took place */
private long lastFrameChange;
/** The frame duration in milliseconds, i.e. how long any given frame of animation lasts */
private long frameDuration = 250;
/** The frame duration in milliseconds, i.e. how long any given frame of animation lasts */
private long frameDuration = 250;
/** The current frame of animation being displayed */
private int frameNumber;
/** The current frame of animation being displayed */
private int frameNumber;
/**
* Create a new alien entity
*
* @param game The game in which this entity is being created
* @param x The intial x location of this alien
* @param y The intial y location of this alient
*/
public AlienEntity(Game game, int x, int y) {
super(game.getSprite("alien.gif"), x, y);
/**
* Create a new alien entity
*
* @param game The game in which this entity is being created
* @param x The intial x location of this alien
* @param y The intial y location of this alient
*/
public AlienEntity(Game game, int x, int y) {
super(game.getSprite("alien.gif"), x, y);
// setup the animatin frames
frames[0] = sprite;
frames[1] = game.getSprite("alien2.gif");
frames[2] = sprite;
frames[3] = game.getSprite("alien3.gif");
// setup the animatin frames
frames[0] = sprite;
frames[1] = game.getSprite("alien2.gif");
frames[2] = sprite;
frames[3] = game.getSprite("alien3.gif");
this.game = game;
dx = -moveSpeed;
}
this.game = game;
dx = -moveSpeed;
}
/**
* Request that this alien moved based on time elapsed
*
* @param delta The time that has elapsed since last move
*/
public void move(long delta) {
// since the move tells us how much time has passed
// by we can use it to drive the animation, however
// its the not the prettiest solution
lastFrameChange += delta;
/**
* Request that this alien moved based on time elapsed
*
* @param delta The time that has elapsed since last move
*/
public void move(long delta) {
// since the move tells us how much time has passed
// by we can use it to drive the animation, however
// its the not the prettiest solution
lastFrameChange += delta;
// if we need to change the frame, update the frame number
// and flip over the sprite in use
if (lastFrameChange > frameDuration) {
// reset our frame change time counter
lastFrameChange = 0;
// if we need to change the frame, update the frame number
// and flip over the sprite in use
if (lastFrameChange > frameDuration) {
// reset our frame change time counter
lastFrameChange = 0;
// update the frame
frameNumber++;
if (frameNumber >= frames.length) {
frameNumber = 0;
}
// update the frame
frameNumber++;
if (frameNumber >= frames.length) {
frameNumber = 0;
}
sprite = frames[frameNumber];
}
sprite = frames[frameNumber];
}
// if we have reached the left hand side of the screen and
// are moving left then request a logic update
if ((dx < 0) && (x < LEFT_BORDER)) {
game.updateLogic();
}
// and vice vesa, if we have reached the right hand side of
// the screen and are moving right, request a logic update
if ((dx > 0) && (x > RIGHT_BORDER)) {
game.updateLogic();
}
// if we have reached the left hand side of the screen and
// are moving left then request a logic update
if ((dx < 0) && (x < LEFT_BORDER)) {
game.updateLogic();
}
// and vice vesa, if we have reached the right hand side of
// the screen and are moving right, request a logic update
if ((dx > 0) && (x > RIGHT_BORDER)) {
game.updateLogic();
}
// proceed with normal move
super.move(delta);
}
// proceed with normal move
super.move(delta);
}
/**
* Update the game logic related to aliens
*/
public void doLogic() {
// swap over horizontal movement and move down the
// screen a bit
dx = -dx;
y += DOWNWARD_MOVEMENT;
/**
* Update the game logic related to aliens
*/
public void doLogic() {
// swap over horizontal movement and move down the
// screen a bit
dx = -dx;
y += DOWNWARD_MOVEMENT;
// if we've reached the bottom of the screen then the player
// dies
if (y > BOTTOM_BORDER) {
game.notifyDeath();
}
}
// if we've reached the bottom of the screen then the player
// dies
if (y > BOTTOM_BORDER) {
game.notifyDeath();
}
}
/**
* Notification that this alien has collided with another entity
*
* @param other The other entity
*/
public void collidedWith(Entity other) {
// collisions with aliens are handled elsewhere
}
}
/**
* Notification that this alien has collided with another entity
*
* @param other The other entity
*/
public void collidedWith(Entity other) {
// collisions with aliens are handled elsewhere
}
}
@@ -48,137 +48,136 @@ import java.awt.Rectangle;
*/
public abstract class Entity {
/** The current x location of this entity */
protected float x;
/** The current x location of this entity */
protected float x;
/** The current y location of this entity */
protected float y;
/** The current y location of this entity */
protected float y;
/** The sprite that represents this entity */
protected Sprite sprite;
/** The sprite that represents this entity */
protected Sprite sprite;
/** The current speed of this entity horizontally (pixels/sec) */
protected float dx;
/** The current speed of this entity horizontally (pixels/sec) */
protected float dx;
/** The current speed of this entity vertically (pixels/sec) */
protected float dy;
/** The current speed of this entity vertically (pixels/sec) */
protected float dy;
/** The rectangle used for this entity during collisions resolution */
private Rectangle me = new Rectangle();
/** The rectangle used for this entity during collisions resolution */
private Rectangle me = new Rectangle();
/** The rectangle used for other entities during collision resolution */
private Rectangle him = new Rectangle();
/** The rectangle used for other entities during collision resolution */
private Rectangle him = new Rectangle();
/**
* Construct a entity based on a sprite image and a location.
*
* @param sprite The reference to the image to be displayed for this entity
* @param x The initial x location of this entity
* @param y The initial y location of this entity
*/
protected Entity(Sprite sprite, int x, int y) {
this.sprite = sprite;
this.x = x;
this.y = y;
}
/**
* Construct a entity based on a sprite image and a location.
*
* @param sprite The reference to the image to be displayed for this entity
* @param x The initial x location of this entity
* @param y The initial y location of this entity
*/
protected Entity(Sprite sprite, int x, int y) {
this.sprite = sprite;
this.x = x;
this.y = y;
}
/**
* Request that this entity move itself based on a certain ammount
* of time passing.
*
* @param delta The ammount of time that has passed in milliseconds
*/
public void move(long delta) {
// update the location of the entity based on move speeds
x += (delta * dx) / 1000;
y += (delta * dy) / 1000;
}
/**
* Request that this entity move itself based on a certain ammount
* of time passing.
*
* @param delta The ammount of time that has passed in milliseconds
*/
public void move(long delta) {
// update the location of the entity based on move speeds
x += (delta * dx) / 1000;
y += (delta * dy) / 1000;
}
/**
* Set the horizontal speed of this entity
*
* @param dx The horizontal speed of this entity (pixels/sec)
*/
public void setHorizontalMovement(float dx) {
this.dx = dx;
}
/**
* Set the horizontal speed of this entity
*
* @param dx The horizontal speed of this entity (pixels/sec)
*/
public void setHorizontalMovement(float dx) {
this.dx = dx;
}
/**
* Set the vertical speed of this entity
*
* @param dy The vertical speed of this entity (pixels/sec)
*/
public void setVerticalMovement(float dy) {
this.dy = dy;
}
/**
* Set the vertical speed of this entity
*
* @param dy The vertical speed of this entity (pixels/sec)
*/
public void setVerticalMovement(float dy) {
this.dy = dy;
}
/**
* Get the horizontal speed of this entity
*
* @return The horizontal speed of this entity (pixels/sec)
*/
public float getHorizontalMovement() {
return dx;
}
/**
* Get the horizontal speed of this entity
*
* @return The horizontal speed of this entity (pixels/sec)
*/
public float getHorizontalMovement() {
return dx;
}
/**
* Get the vertical speed of this entity
*
* @return The vertical speed of this entity (pixels/sec)
*/
public float getVerticalMovement() {
return dy;
}
/**
* Get the vertical speed of this entity
*
* @return The vertical speed of this entity (pixels/sec)
*/
public float getVerticalMovement() {
return dy;
}
/**
* Draw this entity to the graphics context provided
*/
public void draw() {
sprite.draw((int) x, (int) y);
}
/**
* Draw this entity to the graphics context provided
*/
public void draw() {
sprite.draw((int) x, (int) y);
}
/**
* Do the logic associated with this entity. This method
* will be called periodically based on game events
*/
public void doLogic() {
}
/**
* Do the logic associated with this entity. This method
* will be called periodically based on game events
*/
public void doLogic() {}
/**
* Get the x location of this entity
*
* @return The x location of this entity
*/
public int getX() {
return (int) x;
}
/**
* Get the x location of this entity
*
* @return The x location of this entity
*/
public int getX() {
return (int) x;
}
/**
* Get the y location of this entity
*
* @return The y location of this entity
*/
public int getY() {
return (int) y;
}
/**
* Get the y location of this entity
*
* @return The y location of this entity
*/
public int getY() {
return (int) y;
}
/**
* Check if this entity collised with another.
*
* @param other The other entity to check collision against
* @return True if the entities collide with each other
*/
public boolean collidesWith(Entity other) {
me.setBounds((int) x, (int) y, sprite.getWidth(), sprite.getHeight());
him.setBounds((int) other.x, (int) other.y, other.sprite.getWidth(), other.sprite.getHeight());
/**
* Check if this entity collised with another.
*
* @param other The other entity to check collision against
* @return True if the entities collide with each other
*/
public boolean collidesWith(Entity other) {
me.setBounds((int) x, (int) y, sprite.getWidth(), sprite.getHeight());
him.setBounds((int) other.x, (int) other.y, other.sprite.getWidth(), other.sprite.getHeight());
return me.intersects(him);
}
return me.intersects(him);
}
/**
* Notification that this entity collided with another.
*
* @param other The entity with which this entity collided.
*/
public abstract void collidedWith(Entity other);
}
/**
* Notification that this entity collided with another.
*
* @param other The entity with which this entity collided.
*/
public abstract void collidedWith(Entity other);
}
File diff suppressed because it is too large. Load diff
@@ -1,31 +1,31 @@
/*
/*
* Copyright (c) 2002-2008 LWJGL Project
* All rights reserved.
*
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* * Neither the name of 'LWJGL' nor the names of
* its contributors may be used to endorse or promote products derived
* * Neither the name of 'LWJGL' nor the names of
* its contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
@@ -33,66 +33,66 @@ package org.lwjglx.test.spaceinvaders;
/**
* The entity that represents the players ship
*
*
* @author Kevin Glass
* @author Brian Matzon
*/
public class ShipEntity extends Entity {
/** Right border at which to disallow further movement */
private static final int RIGHT_BORDER = 750;
/** Left border at which to disallow further movement */
private static final int LEFT_BORDER = 10;
/** The game in which the ship exists */
private Game game;
/**
* Create a new entity to represent the players ship
*
* @param game The game in which the ship is being created
* @param ref The reference to the sprite to show for the ship
* @param x The initial x location of the player's ship
* @param y The initial y location of the player's ship
*/
public ShipEntity(Game game,String ref,int x,int y) {
super(game.getSprite(ref), x, y);
this.game = game;
}
/**
* Request that the ship move itself based on an elapsed ammount of
* time
*
* @param delta The time that has elapsed since last move (ms)
*/
public void move(long delta) {
// if we're moving left and have reached the left hand side
// of the screen, don't move
if ((dx < 0) && (x < LEFT_BORDER)) {
return;
}
// if we're moving right and have reached the right hand side
// of the screen, don't move
if ((dx > 0) && (x > RIGHT_BORDER)) {
return;
}
super.move(delta);
}
/**
* Notification that the player's ship has collided with something
*
* @param other The entity with which the ship has collided
*/
public void collidedWith(Entity other) {
// if its an alien, notify the game that the player
// is dead
if (other instanceof AlienEntity) {
game.notifyDeath();
}
}
}
/** Right border at which to disallow further movement */
private static final int RIGHT_BORDER = 750;
/** Left border at which to disallow further movement */
private static final int LEFT_BORDER = 10;
/** The game in which the ship exists */
private Game game;
/**
* Create a new entity to represent the players ship
*
* @param game The game in which the ship is being created
* @param ref The reference to the sprite to show for the ship
* @param x The initial x location of the player's ship
* @param y The initial y location of the player's ship
*/
public ShipEntity(Game game, String ref, int x, int y) {
super(game.getSprite(ref), x, y);
this.game = game;
}
/**
* Request that the ship move itself based on an elapsed ammount of
* time
*
* @param delta The time that has elapsed since last move (ms)
*/
public void move(long delta) {
// if we're moving left and have reached the left hand side
// of the screen, don't move
if ((dx < 0) && (x < LEFT_BORDER)) {
return;
}
// if we're moving right and have reached the right hand side
// of the screen, don't move
if ((dx > 0) && (x > RIGHT_BORDER)) {
return;
}
super.move(delta);
}
/**
* Notification that the player's ship has collided with something
*
* @param other The entity with which the ship has collided
*/
public void collidedWith(Entity other) {
// if its an alien, notify the game that the player
// is dead
if (other instanceof AlienEntity) {
game.notifyDeath();
}
}
}
@@ -39,82 +39,82 @@ package org.lwjglx.test.spaceinvaders;
*/
public class ShotEntity extends Entity {
/** Top border at which shots are outside */
private static final int TOP_BORDER = -100;
/** Top border at which shots are outside */
private static final int TOP_BORDER = -100;
/** The vertical speed at which the players shot moves */
private float moveSpeed = -300;
/** The vertical speed at which the players shot moves */
private float moveSpeed = -300;
/** The game in which this entity exists */
private Game game;
/** The game in which this entity exists */
private Game game;
/** True if this shot has been "used", i.e. its hit something */
private boolean used;
/** True if this shot has been "used", i.e. its hit something */
private boolean used;
/**
* Create a new shot from the player
*
* @param game The game in which the shot has been created
* @param sprite The sprite representing this shot
* @param x The initial x location of the shot
* @param y The initial y location of the shot
*/
public ShotEntity(Game game, String sprite, int x, int y) {
super(game.getSprite(sprite), x, y);
/**
* Create a new shot from the player
*
* @param game The game in which the shot has been created
* @param sprite The sprite representing this shot
* @param x The initial x location of the shot
* @param y The initial y location of the shot
*/
public ShotEntity(Game game, String sprite, int x, int y) {
super(game.getSprite(sprite), x, y);
this.game = game;
dy = moveSpeed;
}
this.game = game;
dy = moveSpeed;
}
/**
* Reinitializes this entity, for reuse
*
* @param x new x coordinate
* @param y new y coordinate
*/
public void reinitialize(int x, int y) {
this.x = x;
this.y = y;
used = false;
}
/**
* Reinitializes this entity, for reuse
*
* @param x new x coordinate
* @param y new y coordinate
*/
public void reinitialize(int x, int y) {
this.x = x;
this.y = y;
used = false;
}
/**
* Request that this shot moved based on time elapsed
*
* @param delta The time that has elapsed since last move
*/
public void move(long delta) {
// proceed with normal move
super.move(delta);
/**
* Request that this shot moved based on time elapsed
*
* @param delta The time that has elapsed since last move
*/
public void move(long delta) {
// proceed with normal move
super.move(delta);
// if we shot off the screen, remove ourselfs
if (y < TOP_BORDER) {
game.removeEntity(this);
}
}
// if we shot off the screen, remove ourselfs
if (y < TOP_BORDER) {
game.removeEntity(this);
}
}
/**
* Notification that this shot has collided with another
* entity
*
* @param other The other entity with which we've collided
*/
public void collidedWith(Entity other) {
// prevents double kills, if we've already hit something,
// don't collide
if (used) {
return;
}
/**
* Notification that this shot has collided with another
* entity
*
* @param other The other entity with which we've collided
*/
public void collidedWith(Entity other) {
// prevents double kills, if we've already hit something,
// don't collide
if (used) {
return;
}
// if we've hit an alien, kill it!
if (other instanceof AlienEntity) {
// remove the affected entities
game.removeEntity(this);
game.removeEntity(other);
// if we've hit an alien, kill it!
if (other instanceof AlienEntity) {
// remove the affected entities
game.removeEntity(this);
game.removeEntity(other);
// notify the game that the alien has been killed
game.notifyAlienKilled();
used = true;
}
}
}
// notify the game that the alien has been killed
game.notifyAlienKilled();
used = true;
}
}
}
@@ -32,14 +32,12 @@
package org.lwjglx.test.spaceinvaders;
import java.nio.IntBuffer;
import org.lwjgl.BufferUtils;
import org.lwjglx.LWJGLException;
import org.lwjglx.openal.AL;
import org.lwjglx.openal.AL10;
import org.lwjglx.util.WaveData;
/**
* <p>
* Simple sound manager for OpenAL using n sources accessed in
@@ -52,138 +50,137 @@ import org.lwjglx.util.WaveData;
*/
public class SoundManager {
/** We support at most 256 buffers*/
private int[] buffers = new int[256];
/** We support at most 256 buffers*/
private int[] buffers = new int[256];
/** Number of sources is limited tby user (and hardware) */
private int[] sources;
/** Number of sources is limited tby user (and hardware) */
private int[] sources;
/** Our internal scratch buffer */
private IntBuffer scratchBuffer = BufferUtils.createIntBuffer(256);
/** Our internal scratch buffer */
private IntBuffer scratchBuffer = BufferUtils.createIntBuffer(256);
/** Whether we're running in no sound mode */
private boolean soundOutput;
/** Whether we're running in no sound mode */
private boolean soundOutput;
/** Current index in our buffers */
private int bufferIndex;
/** Current index in our buffers */
private int bufferIndex;
/** Current index in our source list */
private int sourceIndex;
/** Current index in our source list */
private int sourceIndex;
/**
* Creates a new SoundManager
*/
public SoundManager() {
}
/**
* Creates a new SoundManager
*/
public SoundManager() {}
/**
* Plays a sound effect
* @param buffer Buffer index to play gotten from addSound
*/
public void playEffect(int buffer) {
if(soundOutput) {
// make sure we never choose last channel, since it is used for special sounds
int channel = sources[(sourceIndex++ % (sources.length-1))];
/**
* Plays a sound effect
* @param buffer Buffer index to play gotten from addSound
*/
public void playEffect(int buffer) {
if (soundOutput) {
// make sure we never choose last channel, since it is used for special sounds
int channel = sources[(sourceIndex++ % (sources.length - 1))];
// link buffer and source, and play it
AL10.alSourcei(channel, AL10.AL_BUFFER, buffers[buffer]);
AL10.alSourcePlay(channel);
// link buffer and source, and play it
AL10.alSourcei(channel, AL10.AL_BUFFER, buffers[buffer]);
AL10.alSourcePlay(channel);
}
}
}
/**
* Plays a sound on last source
* @param buffer Buffer index to play gotten from addSound
*/
public void playSound(int buffer) {
if(soundOutput) {
AL10.alSourcei(sources[sources.length-1], AL10.AL_BUFFER, buffers[buffer]);
AL10.alSourcePlay(sources[sources.length-1]);
/**
* Plays a sound on last source
* @param buffer Buffer index to play gotten from addSound
*/
public void playSound(int buffer) {
if (soundOutput) {
AL10.alSourcei(sources[sources.length - 1], AL10.AL_BUFFER, buffers[buffer]);
AL10.alSourcePlay(sources[sources.length - 1]);
}
}
}
/**
* Whether a sound is playing on last source
* @return true if a source is playing right now on source n
*/
public boolean isPlayingSound() {
return AL10.alGetSourcei(sources[sources.length-1], AL10.AL_SOURCE_STATE) == AL10.AL_PLAYING;
}
/**
* Initializes the SoundManager
*
* @param channels Number of channels to create
*/
public void initialize(int channels) {
try {
AL.create();
// allocate sources
scratchBuffer.limit(channels);
AL10.alGenSources(scratchBuffer);
scratchBuffer.rewind();
scratchBuffer.get(sources = new int[channels]);
// could we allocate all channels?
if(AL10.alGetError() != AL10.AL_NO_ERROR) {
throw new LWJGLException("Unable to allocate " + channels + " sources");
}
// we have sound
soundOutput = true;
} catch (LWJGLException le) {
le.printStackTrace();
System.out.println("Sound disabled");
/**
* Whether a sound is playing on last source
* @return true if a source is playing right now on source n
*/
public boolean isPlayingSound() {
return AL10.alGetSourcei(sources[sources.length - 1], AL10.AL_SOURCE_STATE) == AL10.AL_PLAYING;
}
}
/**
* Adds a sound to the Sound Managers pool
*
* @param path Path to file to load
* @return index into SoundManagers buffer list
*/
public int addSound(String path) {
// Generate 1 buffer entry
scratchBuffer.rewind().position(0).limit(1);
AL10.alGenBuffers(scratchBuffer);
buffers[bufferIndex] = scratchBuffer.get(0);
/**
* Initializes the SoundManager
*
* @param channels Number of channels to create
*/
public void initialize(int channels) {
try {
AL.create();
// load wave data from buffer
WaveData wavefile = WaveData.create("spaceinvaders/" + path);
// allocate sources
scratchBuffer.limit(channels);
AL10.alGenSources(scratchBuffer);
scratchBuffer.rewind();
scratchBuffer.get(sources = new int[channels]);
// copy to buffers
AL10.alBufferData(buffers[bufferIndex], wavefile.format, wavefile.data, wavefile.samplerate);
// could we allocate all channels?
if (AL10.alGetError() != AL10.AL_NO_ERROR) {
throw new LWJGLException("Unable to allocate " + channels + " sources");
}
// unload file again
wavefile.dispose();
// return index for this sound
return bufferIndex++;
}
/**
* Destroy this SoundManager
*/
public void destroy() {
if(soundOutput) {
// stop playing sounds
scratchBuffer.position(0).limit(sources.length);
scratchBuffer.put(sources).flip();
AL10.alSourceStop(scratchBuffer);
// destroy sources
AL10.alDeleteSources(scratchBuffer);
// destroy buffers
scratchBuffer.position(0).limit(bufferIndex);
scratchBuffer.put(buffers, 0, bufferIndex).flip();
AL10.alDeleteBuffers(scratchBuffer);
// destory OpenAL
AL.destroy();
// we have sound
soundOutput = true;
} catch (LWJGLException le) {
le.printStackTrace();
System.out.println("Sound disabled");
}
}
/**
* Adds a sound to the Sound Managers pool
*
* @param path Path to file to load
* @return index into SoundManagers buffer list
*/
public int addSound(String path) {
// Generate 1 buffer entry
scratchBuffer.rewind().position(0).limit(1);
AL10.alGenBuffers(scratchBuffer);
buffers[bufferIndex] = scratchBuffer.get(0);
// load wave data from buffer
WaveData wavefile = WaveData.create("spaceinvaders/" + path);
// copy to buffers
AL10.alBufferData(buffers[bufferIndex], wavefile.format, wavefile.data, wavefile.samplerate);
// unload file again
wavefile.dispose();
// return index for this sound
return bufferIndex++;
}
/**
* Destroy this SoundManager
*/
public void destroy() {
if (soundOutput) {
// stop playing sounds
scratchBuffer.position(0).limit(sources.length);
scratchBuffer.put(sources).flip();
AL10.alSourceStop(scratchBuffer);
// destroy sources
AL10.alDeleteSources(scratchBuffer);
// destroy buffers
scratchBuffer.position(0).limit(bufferIndex);
scratchBuffer.put(buffers, 0, bufferIndex).flip();
AL10.alDeleteBuffers(scratchBuffer);
// destory OpenAL
AL.destroy();
}
}
}
}
@@ -31,10 +31,10 @@
*/
package org.lwjglx.test.spaceinvaders;
import java.io.IOException;
import static org.lwjgl.opengl.GL11.*;
import java.io.IOException;
/**
* Implementation of sprite that uses an OpenGL quad and a texture
* to render a given image to the screen.
@@ -44,84 +44,84 @@ import static org.lwjgl.opengl.GL11.*;
*/
public class Sprite {
/** The texture that stores the image for this sprite */
private Texture texture;
/** The texture that stores the image for this sprite */
private Texture texture;
/** The width in pixels of this sprite */
private int width;
/** The width in pixels of this sprite */
private int width;
/** The height in pixels of this sprite */
private int height;
/** The height in pixels of this sprite */
private int height;
/**
* Create a new sprite from a specified image.
*
* @param loader the texture loader to use
* @param ref A reference to the image on which this sprite should be based
*/
public Sprite(TextureLoader loader, String ref) {
try {
texture = loader.getTexture("spaceinvaders/" + ref);
width = texture.getImageWidth();
height = texture.getImageHeight();
} catch (IOException ioe) {
ioe.printStackTrace();
System.exit(-1);
/**
* Create a new sprite from a specified image.
*
* @param loader the texture loader to use
* @param ref A reference to the image on which this sprite should be based
*/
public Sprite(TextureLoader loader, String ref) {
try {
texture = loader.getTexture("spaceinvaders/" + ref);
width = texture.getImageWidth();
height = texture.getImageHeight();
} catch (IOException ioe) {
ioe.printStackTrace();
System.exit(-1);
}
}
}
/**
* Get the width of this sprite in pixels
*
* @return The width of this sprite in pixels
*/
public int getWidth() {
return texture.getImageWidth();
}
/**
* Get the width of this sprite in pixels
*
* @return The width of this sprite in pixels
*/
public int getWidth() {
return texture.getImageWidth();
}
/**
* Get the height of this sprite in pixels
*
* @return The height of this sprite in pixels
*/
public int getHeight() {
return texture.getImageHeight();
}
/**
* Get the height of this sprite in pixels
*
* @return The height of this sprite in pixels
*/
public int getHeight() {
return texture.getImageHeight();
}
/**
* Draw the sprite at the specified location
*
* @param x The x location at which to draw this sprite
* @param y The y location at which to draw this sprite
*/
public void draw(int x, int y) {
// store the current model matrix
glPushMatrix();
/**
* Draw the sprite at the specified location
*
* @param x The x location at which to draw this sprite
* @param y The y location at which to draw this sprite
*/
public void draw(int x, int y) {
// store the current model matrix
glPushMatrix();
// bind to the appropriate texture for this sprite
texture.bind();
// bind to the appropriate texture for this sprite
texture.bind();
// translate to the right location and prepare to draw
glTranslatef(x, y, 0);
// translate to the right location and prepare to draw
glTranslatef(x, y, 0);
// draw a quad textured to match the sprite
glBegin(GL_QUADS);
{
glTexCoord2f(0, 0);
glVertex2f(0, 0);
// draw a quad textured to match the sprite
glBegin(GL_QUADS);
{
glTexCoord2f(0, 0);
glVertex2f(0, 0);
glTexCoord2f(0, texture.getHeight());
glVertex2f(0, height);
glTexCoord2f(0, texture.getHeight());
glVertex2f(0, height);
glTexCoord2f(texture.getWidth(), texture.getHeight());
glVertex2f(width, height);
glTexCoord2f(texture.getWidth(), texture.getHeight());
glVertex2f(width, height);
glTexCoord2f(texture.getWidth(), 0);
glVertex2f(width, 0);
}
glEnd();
glTexCoord2f(texture.getWidth(), 0);
glVertex2f(width, 0);
}
glEnd();
// restore the model view matrix to prevent contamination
glPopMatrix();
}
}
// restore the model view matrix to prevent contamination
glPopMatrix();
}
}
@@ -48,141 +48,141 @@ import static org.lwjgl.opengl.GL11.*;
*/
public class Texture {
/** The GL target type */
private int target;
/** The GL target type */
private int target;
/** The GL texture ID */
private int textureID;
/** The GL texture ID */
private int textureID;
/** The height of the image */
private int height;
/** The height of the image */
private int height;
/** The width of the image */
private int width;
/** The width of the image */
private int width;
/** The width of the texture */
private int texWidth;
/** The width of the texture */
private int texWidth;
/** The height of the texture */
private int texHeight;
/** The height of the texture */
private int texHeight;
/** The ratio of the width of the image to the texture */
private float widthRatio;
/** The ratio of the width of the image to the texture */
private float widthRatio;
/** The ratio of the height of the image to the texture */
private float heightRatio;
/** The ratio of the height of the image to the texture */
private float heightRatio;
/**
* Create a new texture
*
* @param target The GL target
* @param textureID The GL texture ID
*/
public Texture(int target, int textureID) {
this.target = target;
this.textureID = textureID;
}
/**
* Create a new texture
*
* @param target The GL target
* @param textureID The GL texture ID
*/
public Texture(int target, int textureID) {
this.target = target;
this.textureID = textureID;
}
/**
* Bind the specified GL context to a texture
*/
public void bind() {
glBindTexture(target, textureID);
}
/**
* Bind the specified GL context to a texture
*/
public void bind() {
glBindTexture(target, textureID);
}
/**
* Set the height of the image
*
* @param height The height of the image
*/
public void setHeight(int height) {
this.height = height;
setHeight();
}
/**
* Set the height of the image
*
* @param height The height of the image
*/
public void setHeight(int height) {
this.height = height;
setHeight();
}
/**
* Set the width of the image
*
* @param width The width of the image
*/
public void setWidth(int width) {
this.width = width;
setWidth();
}
/**
* Set the width of the image
*
* @param width The width of the image
*/
public void setWidth(int width) {
this.width = width;
setWidth();
}
/**
* Get the height of the original image
*
* @return The height of the original image
*/
public int getImageHeight() {
return height;
}
/**
* Get the height of the original image
*
* @return The height of the original image
*/
public int getImageHeight() {
return height;
}
/**
* Get the width of the original image
*
* @return The width of the original image
*/
public int getImageWidth() {
return width;
}
/**
* Get the width of the original image
*
* @return The width of the original image
*/
public int getImageWidth() {
return width;
}
/**
* Get the height of the physical texture
*
* @return The height of physical texture
*/
public float getHeight() {
return heightRatio;
}
/**
* Get the height of the physical texture
*
* @return The height of physical texture
*/
public float getHeight() {
return heightRatio;
}
/**
* Get the width of the physical texture
*
* @return The width of physical texture
*/
public float getWidth() {
return widthRatio;
}
/**
* Get the width of the physical texture
*
* @return The width of physical texture
*/
public float getWidth() {
return widthRatio;
}
/**
* Set the height of this texture
*
* @param texHeight The height of the texture
*/
public void setTextureHeight(int texHeight) {
this.texHeight = texHeight;
setHeight();
}
/**
* Set the height of this texture
*
* @param texHeight The height of the texture
*/
public void setTextureHeight(int texHeight) {
this.texHeight = texHeight;
setHeight();
}
/**
* Set the width of this texture
*
* @param texWidth The width of the texture
*/
public void setTextureWidth(int texWidth) {
this.texWidth = texWidth;
setWidth();
}
/**
* Set the width of this texture
*
* @param texWidth The width of the texture
*/
public void setTextureWidth(int texWidth) {
this.texWidth = texWidth;
setWidth();
}
/**
* Set the height of the texture. This will update the
* ratio also.
*/
private void setHeight() {
if (texHeight != 0) {
heightRatio = ((float) height) / texHeight;
}
}
/**
* Set the height of the texture. This will update the
* ratio also.
*/
private void setHeight() {
if (texHeight != 0) {
heightRatio = ((float) height) / texHeight;
}
}
/**
* Set the width of the texture. This will update the
* ratio also.
*/
private void setWidth() {
if (texWidth != 0) {
widthRatio = ((float) width) / texWidth;
}
}
}
/**
* Set the width of the texture. This will update the
* ratio also.
*/
private void setWidth() {
if (texWidth != 0) {
widthRatio = ((float) width) / texWidth;
}
}
}
@@ -31,6 +31,8 @@
*/
package org.lwjglx.test.spaceinvaders;
import static org.lwjgl.opengl.GL11.*;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Image;
@@ -49,13 +51,9 @@ import java.nio.ByteOrder;
import java.nio.IntBuffer;
import java.util.HashMap;
import java.util.Hashtable;
import javax.swing.ImageIcon;
import org.lwjgl.BufferUtils;
import static org.lwjgl.opengl.GL11.*;
/**
* A utility class to load textures for OpenGL. This source is based
* on a texture that can be found in the Java Gaming (www.javagaming.org)
@@ -86,19 +84,21 @@ public class TextureLoader {
* Create a new texture loader based on the game panel
*/
public TextureLoader() {
glAlphaColorModel = new ComponentColorModel(ColorSpace.getInstance(ColorSpace.CS_sRGB),
new int[] {8,8,8,8},
true,
false,
ComponentColorModel.TRANSLUCENT,
DataBuffer.TYPE_BYTE);
glAlphaColorModel = new ComponentColorModel(
ColorSpace.getInstance(ColorSpace.CS_sRGB),
new int[] {8, 8, 8, 8},
true,
false,
ComponentColorModel.TRANSLUCENT,
DataBuffer.TYPE_BYTE);
glColorModel = new ComponentColorModel(ColorSpace.getInstance(ColorSpace.CS_sRGB),
new int[] {8,8,8,0},
false,
false,
ComponentColorModel.OPAQUE,
DataBuffer.TYPE_BYTE);
glColorModel = new ComponentColorModel(
ColorSpace.getInstance(ColorSpace.CS_sRGB),
new int[] {8, 8, 8, 0},
false,
false,
ComponentColorModel.OPAQUE,
DataBuffer.TYPE_BYTE);
}
/**
@@ -107,8 +107,8 @@ public class TextureLoader {
* @return A new texture ID
*/
private int createTextureID() {
glGenTextures(textureIDBuffer);
return textureIDBuffer.get(0);
glGenTextures(textureIDBuffer);
return textureIDBuffer.get(0);
}
/**
@@ -125,13 +125,14 @@ public class TextureLoader {
return tex;
}
tex = getTexture(resourceName,
GL_TEXTURE_2D, // target
GL_RGBA, // dst pixel format
GL_LINEAR, // min filter (unused)
GL_LINEAR);
tex = getTexture(
resourceName,
GL_TEXTURE_2D, // target
GL_RGBA, // dst pixel format
GL_LINEAR, // min filter (unused)
GL_LINEAR);
table.put(resourceName,tex);
table.put(resourceName, tex);
return tex;
}
@@ -148,16 +149,13 @@ public class TextureLoader {
* @return The loaded texture
* @throws IOException Indicates a failure to access the resource
*/
public Texture getTexture(String resourceName,
int target,
int dstPixelFormat,
int minFilter,
int magFilter) throws IOException {
public Texture getTexture(String resourceName, int target, int dstPixelFormat, int minFilter, int magFilter)
throws IOException {
int srcPixelFormat;
// create the texture ID for this texture
int textureID = createTextureID();
Texture texture = new Texture(target,textureID);
Texture texture = new Texture(target, textureID);
// bind this texture
glBindTexture(target, textureID);
@@ -173,7 +171,7 @@ public class TextureLoader {
}
// convert that image into a byte buffer of texture data
ByteBuffer textureBuffer = convertImageData(bufferedImage,texture);
ByteBuffer textureBuffer = convertImageData(bufferedImage, texture);
if (target == GL_TEXTURE_2D) {
glTexParameteri(target, GL_TEXTURE_MIN_FILTER, minFilter);
@@ -181,15 +179,16 @@ public class TextureLoader {
}
// produce a texture from the byte buffer
glTexImage2D(target,
0,
dstPixelFormat,
get2Fold(bufferedImage.getWidth()),
get2Fold(bufferedImage.getHeight()),
0,
srcPixelFormat,
GL_UNSIGNED_BYTE,
textureBuffer );
glTexImage2D(
target,
0,
dstPixelFormat,
get2Fold(bufferedImage.getWidth()),
get2Fold(bufferedImage.getHeight()),
0,
srcPixelFormat,
GL_UNSIGNED_BYTE,
textureBuffer);
return texture;
}
@@ -215,7 +214,7 @@ public class TextureLoader {
* @param texture The texture to store the data into
* @return A buffer containing the data
*/
private ByteBuffer convertImageData(BufferedImage bufferedImage,Texture texture) {
private ByteBuffer convertImageData(BufferedImage bufferedImage, Texture texture) {
ByteBuffer imageBuffer;
WritableRaster raster;
BufferedImage texImage;
@@ -238,18 +237,18 @@ public class TextureLoader {
// create a raster that can be used by OpenGL as a source
// for a texture
if (bufferedImage.getColorModel().hasAlpha()) {
raster = Raster.createInterleavedRaster(DataBuffer.TYPE_BYTE,texWidth,texHeight,4,null);
texImage = new BufferedImage(glAlphaColorModel,raster,false,new Hashtable());
raster = Raster.createInterleavedRaster(DataBuffer.TYPE_BYTE, texWidth, texHeight, 4, null);
texImage = new BufferedImage(glAlphaColorModel, raster, false, new Hashtable());
} else {
raster = Raster.createInterleavedRaster(DataBuffer.TYPE_BYTE,texWidth,texHeight,3,null);
texImage = new BufferedImage(glColorModel,raster,false,new Hashtable());
raster = Raster.createInterleavedRaster(DataBuffer.TYPE_BYTE, texWidth, texHeight, 3, null);
texImage = new BufferedImage(glColorModel, raster, false, new Hashtable());
}
// copy the source image into the produced image
Graphics g = texImage.getGraphics();
g.setColor(new Color(0f,0f,0f,0f));
g.fillRect(0,0,texWidth,texHeight);
g.drawImage(bufferedImage,0,0,null);
g.setColor(new Color(0f, 0f, 0f, 0f));
g.fillRect(0, 0, texWidth, texHeight);
g.drawImage(bufferedImage, 0, 0, null);
// build a byte buffer from the temporary image
// that be used by OpenGL to produce a texture.
@@ -281,7 +280,8 @@ public class TextureLoader {
// we are now using good oldfashioned ImageIcon to load
// images and the paint it on top of a new BufferedImage
Image img = new ImageIcon(url).getImage();
BufferedImage bufferedImage = new BufferedImage(img.getWidth(null), img.getHeight(null), BufferedImage.TYPE_INT_RGB);
BufferedImage bufferedImage =
new BufferedImage(img.getWidth(null), img.getHeight(null), BufferedImage.TYPE_INT_RGB);
Graphics g = bufferedImage.getGraphics();
g.drawImage(img, 0, 0, null);
g.dispose();
+162 -175
View File
@@ -34,7 +34,6 @@ package org.lwjglx.util;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import org.lwjglx.LWJGLException;
import org.lwjglx.LWJGLUtil;
import org.lwjglx.opengl.DisplayMode;
@@ -48,196 +47,184 @@ import org.lwjglx.opengl.DisplayMode;
*/
public final class Display {
private static final boolean DEBUG = false;
private static final boolean DEBUG = false;
/**
* Determine the available display modes that match the specified minimum and maximum criteria.
* If any given criterium is specified as -1 then it is ignored.
*
* @param minWidth the minimum display resolution in pixels
* @param minHeight the minimum display resolution in pixels
* @param maxWidth the maximum display resolution in pixels
* @param maxHeight the maximum display resolution in pixels
* @param minBPP the minimum bit depth per pixel
* @param maxBPP the maximum bit depth per pixel
* @param minFreq the minimum display frequency in Hz
* @param maxFreq the maximum display frequency in Hz
* @return an array of matching display modes
*/
public static DisplayMode[] getAvailableDisplayModes(int minWidth, int minHeight, int maxWidth, int maxHeight, int minBPP, int maxBPP,
int minFreq, int maxFreq) throws LWJGLException
{
// First get the available display modes
DisplayMode[] modes = org.lwjglx.opengl.Display.getAvailableDisplayModes();
/**
* Determine the available display modes that match the specified minimum and maximum criteria.
* If any given criterium is specified as -1 then it is ignored.
*
* @param minWidth the minimum display resolution in pixels
* @param minHeight the minimum display resolution in pixels
* @param maxWidth the maximum display resolution in pixels
* @param maxHeight the maximum display resolution in pixels
* @param minBPP the minimum bit depth per pixel
* @param maxBPP the maximum bit depth per pixel
* @param minFreq the minimum display frequency in Hz
* @param maxFreq the maximum display frequency in Hz
* @return an array of matching display modes
*/
public static DisplayMode[] getAvailableDisplayModes(
int minWidth, int minHeight, int maxWidth, int maxHeight, int minBPP, int maxBPP, int minFreq, int maxFreq)
throws LWJGLException {
// First get the available display modes
DisplayMode[] modes = org.lwjglx.opengl.Display.getAvailableDisplayModes();
if (LWJGLUtil.DEBUG || DEBUG) {
System.out.println("Available screen modes:");
for ( DisplayMode mode : modes ) {
System.out.println(mode);
}
}
if (LWJGLUtil.DEBUG || DEBUG) {
System.out.println("Available screen modes:");
for (DisplayMode mode : modes) {
System.out.println(mode);
}
}
ArrayList<DisplayMode> matches = new ArrayList<DisplayMode>(modes.length);
ArrayList<DisplayMode> matches = new ArrayList<DisplayMode>(modes.length);
for (int i = 0; i < modes.length; i ++) {
assert modes[i] != null : ""+i+" "+modes.length;
if (minWidth != -1 && modes[i].getWidth() < minWidth)
continue;
if (maxWidth != -1 && modes[i].getWidth() > maxWidth)
continue;
if (minHeight != -1 && modes[i].getHeight() < minHeight)
continue;
if (maxHeight != -1 && modes[i].getHeight() > maxHeight)
continue;
if (minBPP != -1 && modes[i].getBitsPerPixel() < minBPP)
continue;
if (maxBPP != -1 && modes[i].getBitsPerPixel() > maxBPP)
continue;
//if (modes[i].bpp == 24)
// continue;
if (modes[i].getFrequency() != 0) {
if (minFreq != -1 && modes[i].getFrequency() < minFreq)
continue;
if (maxFreq != -1 && modes[i].getFrequency() > maxFreq)
continue;
}
matches.add(modes[i]);
}
for (int i = 0; i < modes.length; i++) {
assert modes[i] != null : "" + i + " " + modes.length;
if (minWidth != -1 && modes[i].getWidth() < minWidth) continue;
if (maxWidth != -1 && modes[i].getWidth() > maxWidth) continue;
if (minHeight != -1 && modes[i].getHeight() < minHeight) continue;
if (maxHeight != -1 && modes[i].getHeight() > maxHeight) continue;
if (minBPP != -1 && modes[i].getBitsPerPixel() < minBPP) continue;
if (maxBPP != -1 && modes[i].getBitsPerPixel() > maxBPP) continue;
// if (modes[i].bpp == 24)
// continue;
if (modes[i].getFrequency() != 0) {
if (minFreq != -1 && modes[i].getFrequency() < minFreq) continue;
if (maxFreq != -1 && modes[i].getFrequency() > maxFreq) continue;
}
matches.add(modes[i]);
}
DisplayMode[] ret = new DisplayMode[matches.size()];
matches.toArray(ret);
if (LWJGLUtil.DEBUG && DEBUG) {
System.out.println("Filtered screen modes:");
for ( DisplayMode mode : ret ) {
System.out.println(mode);
}
}
DisplayMode[] ret = new DisplayMode[matches.size()];
matches.toArray(ret);
if (LWJGLUtil.DEBUG && DEBUG) {
System.out.println("Filtered screen modes:");
for (DisplayMode mode : ret) {
System.out.println(mode);
}
}
return ret;
}
return ret;
}
/**
* Create the display by choosing from a list of display modes based on an order of preference.
* You must supply a list of allowable display modes, probably by calling getAvailableDisplayModes(),
* and an array with the order in which you would like them sorted in descending order.
* This method attempts to create the topmost display mode; if that fails, it will try the next one,
* and so on, until there are no modes left. If no mode is set at the end, an exception is thrown.
* @param dm a list of display modes to choose from
* @param param the names of the DisplayMode fields in the order in which you would like them sorted.
* @return the chosen display mode
* @throws NoSuchFieldException if one of the params is not a field in DisplayMode
* @throws Exception if no display mode could be set
* @see org.lwjgl.opengl.DisplayMode
*/
public static DisplayMode setDisplayMode(DisplayMode[] dm, final String[] param) throws Exception {
/**
* Create the display by choosing from a list of display modes based on an order of preference.
* You must supply a list of allowable display modes, probably by calling getAvailableDisplayModes(),
* and an array with the order in which you would like them sorted in descending order.
* This method attempts to create the topmost display mode; if that fails, it will try the next one,
* and so on, until there are no modes left. If no mode is set at the end, an exception is thrown.
* @param dm a list of display modes to choose from
* @param param the names of the DisplayMode fields in the order in which you would like them sorted.
* @return the chosen display mode
* @throws NoSuchFieldException if one of the params is not a field in DisplayMode
* @throws Exception if no display mode could be set
* @see org.lwjgl.opengl.DisplayMode
*/
public static DisplayMode setDisplayMode(DisplayMode[] dm, final String[] param) throws Exception {
class FieldAccessor {
final String fieldName;
final int order;
final int preferred;
final boolean usePreferred;
FieldAccessor(String fieldName, int order, int preferred, boolean usePreferred) {
this.fieldName = fieldName;
this.order = order;
this.preferred = preferred;
this.usePreferred = usePreferred;
}
int getInt(DisplayMode mode) {
if ("width".equals(fieldName)) {
return mode.getWidth();
}
if ("height".equals(fieldName)) {
return mode.getHeight();
}
if ("freq".equals(fieldName)) {
return mode.getFrequency();
}
if ("bpp".equals(fieldName)) {
return mode.getBitsPerPixel();
}
throw new IllegalArgumentException("Unknown field "+fieldName);
}
}
class FieldAccessor {
final String fieldName;
final int order;
final int preferred;
final boolean usePreferred;
class Sorter implements Comparator<DisplayMode> {
FieldAccessor(String fieldName, int order, int preferred, boolean usePreferred) {
this.fieldName = fieldName;
this.order = order;
this.preferred = preferred;
this.usePreferred = usePreferred;
}
final FieldAccessor[] accessors;
int getInt(DisplayMode mode) {
if ("width".equals(fieldName)) {
return mode.getWidth();
}
if ("height".equals(fieldName)) {
return mode.getHeight();
}
if ("freq".equals(fieldName)) {
return mode.getFrequency();
}
if ("bpp".equals(fieldName)) {
return mode.getBitsPerPixel();
}
throw new IllegalArgumentException("Unknown field " + fieldName);
}
}
Sorter() {
accessors = new FieldAccessor[param.length];
for (int i = 0; i < accessors.length; i ++) {
int idx = param[i].indexOf('=');
if (idx > 0) {
accessors[i] = new FieldAccessor(param[i].substring(0, idx), 0, Integer.parseInt(param[i].substring(idx + 1, param[i].length())), true);
} else if (param[i].charAt(0) == '-') {
accessors[i] = new FieldAccessor(param[i].substring(1), -1, 0, false);
} else {
accessors[i] = new FieldAccessor(param[i], 1, 0, false);
}
}
}
class Sorter implements Comparator<DisplayMode> {
/**
* @see java.util.Comparator#compare(java.lang.Object, java.lang.Object)
*/
public int compare(DisplayMode dm1, DisplayMode dm2) {
for ( FieldAccessor accessor : accessors ) {
int f1 = accessor.getInt(dm1);
int f2 = accessor.getInt(dm2);
final FieldAccessor[] accessors;
if ( accessor.usePreferred && f1 != f2 ) {
if ( f1 == accessor.preferred )
return -1;
else if ( f2 == accessor.preferred )
return 1;
else {
// Score according to the difference between the values
int absf1 = Math.abs(f1 - accessor.preferred);
int absf2 = Math.abs(f2 - accessor.preferred);
if ( absf1 < absf2 )
return -1;
else if ( absf1 > absf2 )
return 1;
else
continue;
}
} else if ( f1 < f2 )
return accessor.order;
else if ( f1 == f2 )
continue;
else
return -accessor.order;
}
Sorter() {
accessors = new FieldAccessor[param.length];
for (int i = 0; i < accessors.length; i++) {
int idx = param[i].indexOf('=');
if (idx > 0) {
accessors[i] = new FieldAccessor(
param[i].substring(0, idx),
0,
Integer.parseInt(param[i].substring(idx + 1, param[i].length())),
true);
} else if (param[i].charAt(0) == '-') {
accessors[i] = new FieldAccessor(param[i].substring(1), -1, 0, false);
} else {
accessors[i] = new FieldAccessor(param[i], 1, 0, false);
}
}
}
return 0;
}
}
/**
* @see java.util.Comparator#compare(java.lang.Object, java.lang.Object)
*/
public int compare(DisplayMode dm1, DisplayMode dm2) {
for (FieldAccessor accessor : accessors) {
int f1 = accessor.getInt(dm1);
int f2 = accessor.getInt(dm2);
// Sort the display modes
Arrays.sort(dm, new Sorter());
if (accessor.usePreferred && f1 != f2) {
if (f1 == accessor.preferred) return -1;
else if (f2 == accessor.preferred) return 1;
else {
// Score according to the difference between the values
int absf1 = Math.abs(f1 - accessor.preferred);
int absf2 = Math.abs(f2 - accessor.preferred);
if (absf1 < absf2) return -1;
else if (absf1 > absf2) return 1;
else continue;
}
} else if (f1 < f2) return accessor.order;
else if (f1 == f2) continue;
else return -accessor.order;
}
// Try them out in the appropriate order
if (LWJGLUtil.DEBUG || DEBUG) {
System.out.println("Sorted display modes:");
for ( DisplayMode aDm : dm ) {
System.out.println(aDm);
}
}
for ( DisplayMode aDm : dm ) {
try {
if ( LWJGLUtil.DEBUG || DEBUG )
System.out.println("Attempting to set displaymode: " + aDm);
org.lwjglx.opengl.Display.setDisplayMode(aDm);
return aDm;
} catch (Exception e) {
if ( LWJGLUtil.DEBUG || DEBUG ) {
System.out.println("Failed to set display mode to " + aDm);
e.printStackTrace();
}
}
}
return 0;
}
}
throw new Exception("Failed to set display mode.");
}
// Sort the display modes
Arrays.sort(dm, new Sorter());
// Try them out in the appropriate order
if (LWJGLUtil.DEBUG || DEBUG) {
System.out.println("Sorted display modes:");
for (DisplayMode aDm : dm) {
System.out.println(aDm);
}
}
for (DisplayMode aDm : dm) {
try {
if (LWJGLUtil.DEBUG || DEBUG) System.out.println("Attempting to set displaymode: " + aDm);
org.lwjglx.opengl.Display.setDisplayMode(aDm);
return aDm;
} catch (Exception e) {
if (LWJGLUtil.DEBUG || DEBUG) {
System.out.println("Failed to set display mode to " + aDm);
e.printStackTrace();
}
}
}
throw new Exception("Failed to set display mode.");
}
}
+197 -201
View File
@@ -1,31 +1,31 @@
/*
/*
* Copyright (c) 2002-2008 LWJGL Project
* All rights reserved.
*
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* * Neither the name of 'LWJGL' nor the names of
* its contributors may be used to endorse or promote products derived
* * Neither the name of 'LWJGL' nor the names of
* its contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
@@ -39,14 +39,12 @@ import java.net.URL;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.ShortBuffer;
import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import org.lwjgl.openal.AL10;
//import com.sun.media.sound.WaveFileReader;
// import com.sun.media.sound.WaveFileReader;
/**
*
@@ -57,202 +55,200 @@ import org.lwjgl.openal.AL10;
* $Id$
*/
public class WaveData {
/** actual wave data */
public final ByteBuffer data;
/** actual wave data */
public final ByteBuffer data;
/** format type of data */
public final int format;
/** format type of data */
public final int format;
/** sample rate of data */
public final int samplerate;
/** sample rate of data */
public final int samplerate;
/**
* Creates a new WaveData
*
* @param data actual wavedata
* @param format format of wave data
* @param samplerate sample rate of data
*/
private WaveData(ByteBuffer data, int format, int samplerate) {
this.data = data;
this.format = format;
this.samplerate = samplerate;
}
/**
* Creates a new WaveData
*
* @param data actual wavedata
* @param format format of wave data
* @param samplerate sample rate of data
*/
private WaveData(ByteBuffer data, int format, int samplerate) {
this.data = data;
this.format = format;
this.samplerate = samplerate;
}
/**
* Disposes the wavedata
*/
public void dispose() {
data.clear();
}
/**
* Disposes the wavedata
*/
public void dispose() {
data.clear();
}
/**
* Creates a WaveData container from the specified url
*
* @param path URL to file
* @return WaveData containing data, or null if a failure occured
*/
public static WaveData create(URL path) {
try {
// due to an issue with AudioSystem.getAudioInputStream
// and mixing unsigned and signed code
// we will use the reader directly
return create(AudioSystem.getAudioInputStream(path));
//WaveFileReader wfr = new WaveFileReader();
//return create(wfr.getAudioInputStream(new BufferedInputStream(path.openStream())));
} catch (Exception e) {
org.lwjgl.LWJGLUtil.log("Unable to create from: " + path + ", " + e.getMessage());
return null;
}
}
/**
* Creates a WaveData container from the specified in the classpath
*
* @param path path to file (relative, and in classpath)
* @return WaveData containing data, or null if a failure occured
*/
public static WaveData create(String path) {
return create(Thread.currentThread().getContextClassLoader().getResource(path));
}
/**
* Creates a WaveData container from the specified inputstream
*
* @param is InputStream to read from
* @return WaveData containing data, or null if a failure occured
*/
public static WaveData create(InputStream is) {
try {
return create(
AudioSystem.getAudioInputStream(is));
} catch (Exception e) {
org.lwjgl.LWJGLUtil.log("Unable to create from inputstream, " + e.getMessage());
return null;
}
}
/**
* Creates a WaveData container from the specified bytes
*
* @param buffer array of bytes containing the complete wave file
* @return WaveData containing data, or null if a failure occured
*/
public static WaveData create(byte[] buffer) {
try {
return create(
AudioSystem.getAudioInputStream(
new BufferedInputStream(new ByteArrayInputStream(buffer))));
} catch (Exception e) {
org.lwjgl.LWJGLUtil.log("Unable to create from byte array, " + e.getMessage());
return null;
}
}
/**
* Creates a WaveData container from the specified ByetBuffer.
* If the buffer is backed by an array, it will be used directly,
* else the contents of the buffer will be copied using get(byte[]).
*
* @param buffer ByteBuffer containing sound file
* @return WaveData containing data, or null if a failure occured
*/
public static WaveData create(ByteBuffer buffer) {
try {
byte[] bytes = null;
if(buffer.hasArray()) {
bytes = buffer.array();
} else {
bytes = new byte[buffer.capacity()];
buffer.get(bytes);
}
return create(bytes);
} catch (Exception e) {
org.lwjgl.LWJGLUtil.log("Unable to create from ByteBuffer, " + e.getMessage());
return null;
}
}
/**
* Creates a WaveData container from the specified url
*
* @param path URL to file
* @return WaveData containing data, or null if a failure occured
*/
public static WaveData create(URL path) {
try {
// due to an issue with AudioSystem.getAudioInputStream
// and mixing unsigned and signed code
// we will use the reader directly
return create(AudioSystem.getAudioInputStream(path));
// WaveFileReader wfr = new WaveFileReader();
// return create(wfr.getAudioInputStream(new BufferedInputStream(path.openStream())));
} catch (Exception e) {
org.lwjgl.LWJGLUtil.log("Unable to create from: " + path + ", " + e.getMessage());
return null;
}
}
/**
* Creates a WaveData container from the specified stream
*
* @param ais AudioInputStream to read from
* @return WaveData containing data, or null if a failure occured
*/
public static WaveData create(AudioInputStream ais) {
//get format of data
AudioFormat audioformat = ais.getFormat();
/**
* Creates a WaveData container from the specified in the classpath
*
* @param path path to file (relative, and in classpath)
* @return WaveData containing data, or null if a failure occured
*/
public static WaveData create(String path) {
return create(Thread.currentThread().getContextClassLoader().getResource(path));
}
// get channels
int channels = 0;
if (audioformat.getChannels() == 1) {
if (audioformat.getSampleSizeInBits() == 8) {
channels = AL10.AL_FORMAT_MONO8;
} else if (audioformat.getSampleSizeInBits() == 16) {
channels = AL10.AL_FORMAT_MONO16;
} else {
assert false : "Illegal sample size";
}
} else if (audioformat.getChannels() == 2) {
if (audioformat.getSampleSizeInBits() == 8) {
channels = AL10.AL_FORMAT_STEREO8;
} else if (audioformat.getSampleSizeInBits() == 16) {
channels = AL10.AL_FORMAT_STEREO16;
} else {
assert false : "Illegal sample size";
}
} else {
assert false : "Only mono or stereo is supported";
}
/**
* Creates a WaveData container from the specified inputstream
*
* @param is InputStream to read from
* @return WaveData containing data, or null if a failure occured
*/
public static WaveData create(InputStream is) {
try {
return create(AudioSystem.getAudioInputStream(is));
} catch (Exception e) {
org.lwjgl.LWJGLUtil.log("Unable to create from inputstream, " + e.getMessage());
return null;
}
}
//read data into buffer
ByteBuffer buffer = null;
try {
int available = ais.available();
if(available <= 0) {
available = ais.getFormat().getChannels() * (int) ais.getFrameLength() * ais.getFormat().getSampleSizeInBits() / 8;
}
byte[] buf = new byte[ais.available()];
int read = 0, total = 0;
while ((read = ais.read(buf, total, buf.length - total)) != -1
&& total < buf.length) {
total += read;
}
buffer = convertAudioBytes(buf, audioformat.getSampleSizeInBits() == 16, audioformat.isBigEndian() ? ByteOrder.BIG_ENDIAN : ByteOrder.LITTLE_ENDIAN);
} catch (IOException ioe) {
return null;
}
/**
* Creates a WaveData container from the specified bytes
*
* @param buffer array of bytes containing the complete wave file
* @return WaveData containing data, or null if a failure occured
*/
public static WaveData create(byte[] buffer) {
try {
return create(AudioSystem.getAudioInputStream(new BufferedInputStream(new ByteArrayInputStream(buffer))));
} catch (Exception e) {
org.lwjgl.LWJGLUtil.log("Unable to create from byte array, " + e.getMessage());
return null;
}
}
/**
* Creates a WaveData container from the specified ByetBuffer.
* If the buffer is backed by an array, it will be used directly,
* else the contents of the buffer will be copied using get(byte[]).
*
* @param buffer ByteBuffer containing sound file
* @return WaveData containing data, or null if a failure occured
*/
public static WaveData create(ByteBuffer buffer) {
try {
byte[] bytes = null;
//create our result
WaveData wavedata =
new WaveData(buffer, channels, (int) audioformat.getSampleRate());
if (buffer.hasArray()) {
bytes = buffer.array();
} else {
bytes = new byte[buffer.capacity()];
buffer.get(bytes);
}
return create(bytes);
} catch (Exception e) {
org.lwjgl.LWJGLUtil.log("Unable to create from ByteBuffer, " + e.getMessage());
return null;
}
}
//close stream
try {
ais.close();
} catch (IOException ioe) {
}
/**
* Creates a WaveData container from the specified stream
*
* @param ais AudioInputStream to read from
* @return WaveData containing data, or null if a failure occured
*/
public static WaveData create(AudioInputStream ais) {
// get format of data
AudioFormat audioformat = ais.getFormat();
return wavedata;
}
// get channels
int channels = 0;
if (audioformat.getChannels() == 1) {
if (audioformat.getSampleSizeInBits() == 8) {
channels = AL10.AL_FORMAT_MONO8;
} else if (audioformat.getSampleSizeInBits() == 16) {
channels = AL10.AL_FORMAT_MONO16;
} else {
assert false : "Illegal sample size";
}
} else if (audioformat.getChannels() == 2) {
if (audioformat.getSampleSizeInBits() == 8) {
channels = AL10.AL_FORMAT_STEREO8;
} else if (audioformat.getSampleSizeInBits() == 16) {
channels = AL10.AL_FORMAT_STEREO16;
} else {
assert false : "Illegal sample size";
}
} else {
assert false : "Only mono or stereo is supported";
}
private static ByteBuffer convertAudioBytes(byte[] audio_bytes, boolean two_bytes_data, ByteOrder order) {
ByteBuffer dest = ByteBuffer.allocateDirect(audio_bytes.length);
dest.order(ByteOrder.nativeOrder());
ByteBuffer src = ByteBuffer.wrap(audio_bytes);
src.order(order);
if (two_bytes_data) {
ShortBuffer dest_short = dest.asShortBuffer();
ShortBuffer src_short = src.asShortBuffer();
while (src_short.hasRemaining())
dest_short.put(src_short.get());
} else {
while (src.hasRemaining())
dest.put(src.get());
}
dest.rewind();
return dest;
}
// read data into buffer
ByteBuffer buffer = null;
try {
int available = ais.available();
if (available <= 0) {
available = ais.getFormat().getChannels()
* (int) ais.getFrameLength()
* ais.getFormat().getSampleSizeInBits()
/ 8;
}
byte[] buf = new byte[ais.available()];
int read = 0, total = 0;
while ((read = ais.read(buf, total, buf.length - total)) != -1 && total < buf.length) {
total += read;
}
buffer = convertAudioBytes(
buf,
audioformat.getSampleSizeInBits() == 16,
audioformat.isBigEndian() ? ByteOrder.BIG_ENDIAN : ByteOrder.LITTLE_ENDIAN);
} catch (IOException ioe) {
return null;
}
// create our result
WaveData wavedata = new WaveData(buffer, channels, (int) audioformat.getSampleRate());
// close stream
try {
ais.close();
} catch (IOException ioe) {
}
return wavedata;
}
private static ByteBuffer convertAudioBytes(byte[] audio_bytes, boolean two_bytes_data, ByteOrder order) {
ByteBuffer dest = ByteBuffer.allocateDirect(audio_bytes.length);
dest.order(ByteOrder.nativeOrder());
ByteBuffer src = ByteBuffer.wrap(audio_bytes);
src.order(order);
if (two_bytes_data) {
ShortBuffer dest_short = dest.asShortBuffer();
ShortBuffer src_short = src.asShortBuffer();
while (src_short.hasRemaining()) dest_short.put(src_short.get());
} else {
while (src.hasRemaining()) dest.put(src.get());
}
dest.rewind();
return dest;
}
}
+149 -149
View File
@@ -43,159 +43,159 @@ import static org.lwjglx.util.glu.GLU.*;
*/
public class Cylinder extends Quadric {
/**
* Constructor for Cylinder.
*/
public Cylinder() {
super();
}
/**
* Constructor for Cylinder.
*/
public Cylinder() {
super();
}
/**
* draws a cylinder oriented along the z axis. The base of the
* cylinder is placed at z = 0, and the top at z=height. Like a sphere, a
* cylinder is subdivided around the z axis into slices, and along the z axis
* into stacks.
*
* Note that if topRadius is set to zero, then this routine will generate a
* cone.
*
* If the orientation is set to GLU.OUTSIDE (with glu.quadricOrientation), then
* any generated normals point away from the z axis. Otherwise, they point
* toward the z axis.
*
* If texturing is turned on (with glu.quadricTexture), then texture
* coordinates are generated so that t ranges linearly from 0.0 at z = 0 to
* 1.0 at z = height, and s ranges from 0.0 at the +y axis, to 0.25 at the +x
* axis, to 0.5 at the -y axis, to 0.75 at the -x axis, and back to 1.0 at the
* +y axis.
*
* @param baseRadius Specifies the radius of the cylinder at z = 0.
* @param topRadius Specifies the radius of the cylinder at z = height.
* @param height Specifies the height of the cylinder.
* @param slices Specifies the number of subdivisions around the z axis.
* @param stacks Specifies the number of subdivisions along the z axis.
*/
public void draw(float baseRadius, float topRadius, float height, int slices, int stacks) {
/**
* draws a cylinder oriented along the z axis. The base of the
* cylinder is placed at z = 0, and the top at z=height. Like a sphere, a
* cylinder is subdivided around the z axis into slices, and along the z axis
* into stacks.
*
* Note that if topRadius is set to zero, then this routine will generate a
* cone.
*
* If the orientation is set to GLU.OUTSIDE (with glu.quadricOrientation), then
* any generated normals point away from the z axis. Otherwise, they point
* toward the z axis.
*
* If texturing is turned on (with glu.quadricTexture), then texture
* coordinates are generated so that t ranges linearly from 0.0 at z = 0 to
* 1.0 at z = height, and s ranges from 0.0 at the +y axis, to 0.25 at the +x
* axis, to 0.5 at the -y axis, to 0.75 at the -x axis, and back to 1.0 at the
* +y axis.
*
* @param baseRadius Specifies the radius of the cylinder at z = 0.
* @param topRadius Specifies the radius of the cylinder at z = height.
* @param height Specifies the height of the cylinder.
* @param slices Specifies the number of subdivisions around the z axis.
* @param stacks Specifies the number of subdivisions along the z axis.
*/
public void draw(float baseRadius, float topRadius, float height, int slices, int stacks) {
float da, r, dr, dz;
float x, y, z, nz, nsign;
int i, j;
float da, r, dr, dz;
float x, y, z, nz, nsign;
int i, j;
if (super.orientation == GLU_INSIDE) {
nsign = -1.0f;
} else {
nsign = 1.0f;
}
if (super.orientation == GLU_INSIDE) {
nsign = -1.0f;
} else {
nsign = 1.0f;
}
da = 2.0f * PI / slices;
dr = (topRadius - baseRadius) / stacks;
dz = height / stacks;
nz = (baseRadius - topRadius) / height;
// Z component of normal vectors
da = 2.0f * PI / slices;
dr = (topRadius - baseRadius) / stacks;
dz = height / stacks;
nz = (baseRadius - topRadius) / height;
// Z component of normal vectors
if (super.drawStyle == GLU_POINT) {
glBegin(GL_POINTS);
for (i = 0; i < slices; i++) {
x = cos((i * da));
y = sin((i * da));
normal3f(x * nsign, y * nsign, nz * nsign);
if (super.drawStyle == GLU_POINT) {
glBegin(GL_POINTS);
for (i = 0; i < slices; i++) {
x = cos((i * da));
y = sin((i * da));
normal3f(x * nsign, y * nsign, nz * nsign);
z = 0.0f;
r = baseRadius;
for (j = 0; j <= stacks; j++) {
glVertex3f((x * r), (y * r), z);
z += dz;
r += dr;
}
}
glEnd();
} else if (super.drawStyle == GLU_LINE || super.drawStyle == GLU_SILHOUETTE) {
// Draw rings
if (super.drawStyle == GLU_LINE) {
z = 0.0f;
r = baseRadius;
for (j = 0; j <= stacks; j++) {
glBegin(GL_LINE_LOOP);
for (i = 0; i < slices; i++) {
x = cos((i * da));
y = sin((i * da));
normal3f(x * nsign, y * nsign, nz * nsign);
glVertex3f((x * r), (y * r), z);
}
glEnd();
z += dz;
r += dr;
}
} else {
// draw one ring at each end
if (baseRadius != 0.0) {
glBegin(GL_LINE_LOOP);
for (i = 0; i < slices; i++) {
x = cos((i * da));
y = sin((i * da));
normal3f(x * nsign, y * nsign, nz * nsign);
glVertex3f((x * baseRadius), (y * baseRadius), 0.0f);
}
glEnd();
glBegin(GL_LINE_LOOP);
for (i = 0; i < slices; i++) {
x = cos((i * da));
y = sin((i * da));
normal3f(x * nsign, y * nsign, nz * nsign);
glVertex3f((x * topRadius), (y * topRadius), height);
}
glEnd();
}
}
// draw length lines
glBegin(GL_LINES);
for (i = 0; i < slices; i++) {
x = cos((i * da));
y = sin((i * da));
normal3f(x * nsign, y * nsign, nz * nsign);
glVertex3f((x * baseRadius), (y * baseRadius), 0.0f);
glVertex3f((x * topRadius), (y * topRadius), (height));
}
glEnd();
} else if (super.drawStyle == GLU_FILL) {
float ds = 1.0f / slices;
float dt = 1.0f / stacks;
float t = 0.0f;
z = 0.0f;
r = baseRadius;
for (j = 0; j < stacks; j++) {
float s = 0.0f;
glBegin(GL_QUAD_STRIP);
for (i = 0; i <= slices; i++) {
if (i == slices) {
x = sin(0.0f);
y = cos(0.0f);
} else {
x = sin((i * da));
y = cos((i * da));
}
if (nsign == 1.0f) {
normal3f((x * nsign), (y * nsign), (nz * nsign));
TXTR_COORD(s, t);
glVertex3f((x * r), (y * r), z);
normal3f((x * nsign), (y * nsign), (nz * nsign));
TXTR_COORD(s, t + dt);
glVertex3f((x * (r + dr)), (y * (r + dr)), (z + dz));
} else {
normal3f(x * nsign, y * nsign, nz * nsign);
TXTR_COORD(s, t);
glVertex3f((x * r), (y * r), z);
normal3f(x * nsign, y * nsign, nz * nsign);
TXTR_COORD(s, t + dt);
glVertex3f((x * (r + dr)), (y * (r + dr)), (z + dz));
}
s += ds;
} // for slices
glEnd();
r += dr;
t += dt;
z += dz;
} // for stacks
}
}
z = 0.0f;
r = baseRadius;
for (j = 0; j <= stacks; j++) {
glVertex3f((x * r), (y * r), z);
z += dz;
r += dr;
}
}
glEnd();
} else if (super.drawStyle == GLU_LINE || super.drawStyle == GLU_SILHOUETTE) {
// Draw rings
if (super.drawStyle == GLU_LINE) {
z = 0.0f;
r = baseRadius;
for (j = 0; j <= stacks; j++) {
glBegin(GL_LINE_LOOP);
for (i = 0; i < slices; i++) {
x = cos((i * da));
y = sin((i * da));
normal3f(x * nsign, y * nsign, nz * nsign);
glVertex3f((x * r), (y * r), z);
}
glEnd();
z += dz;
r += dr;
}
} else {
// draw one ring at each end
if (baseRadius != 0.0) {
glBegin(GL_LINE_LOOP);
for (i = 0; i < slices; i++) {
x = cos((i * da));
y = sin((i * da));
normal3f(x * nsign, y * nsign, nz * nsign);
glVertex3f((x * baseRadius), (y * baseRadius), 0.0f);
}
glEnd();
glBegin(GL_LINE_LOOP);
for (i = 0; i < slices; i++) {
x = cos((i * da));
y = sin((i * da));
normal3f(x * nsign, y * nsign, nz * nsign);
glVertex3f((x * topRadius), (y * topRadius), height);
}
glEnd();
}
}
// draw length lines
glBegin(GL_LINES);
for (i = 0; i < slices; i++) {
x = cos((i * da));
y = sin((i * da));
normal3f(x * nsign, y * nsign, nz * nsign);
glVertex3f((x * baseRadius), (y * baseRadius), 0.0f);
glVertex3f((x * topRadius), (y * topRadius), (height));
}
glEnd();
} else if (super.drawStyle == GLU_FILL) {
float ds = 1.0f / slices;
float dt = 1.0f / stacks;
float t = 0.0f;
z = 0.0f;
r = baseRadius;
for (j = 0; j < stacks; j++) {
float s = 0.0f;
glBegin(GL_QUAD_STRIP);
for (i = 0; i <= slices; i++) {
if (i == slices) {
x = sin(0.0f);
y = cos(0.0f);
} else {
x = sin((i * da));
y = cos((i * da));
}
if (nsign == 1.0f) {
normal3f((x * nsign), (y * nsign), (nz * nsign));
TXTR_COORD(s, t);
glVertex3f((x * r), (y * r), z);
normal3f((x * nsign), (y * nsign), (nz * nsign));
TXTR_COORD(s, t + dt);
glVertex3f((x * (r + dr)), (y * (r + dr)), (z + dz));
} else {
normal3f(x * nsign, y * nsign, nz * nsign);
TXTR_COORD(s, t);
glVertex3f((x * r), (y * r), z);
normal3f(x * nsign, y * nsign, nz * nsign);
TXTR_COORD(s, t + dt);
glVertex3f((x * (r + dr)), (y * (r + dr)), (z + dz));
}
s += ds;
} // for slices
glEnd();
r += dr;
t += dt;
z += dz;
} // for stacks
}
}
}
+134 -146
View File
@@ -43,12 +43,12 @@ import static org.lwjglx.util.glu.GLU.*;
*/
public class Disk extends Quadric {
/**
* Constructor for Disk.
*/
public Disk() {
super();
}
/**
* Constructor for Disk.
*/
public Disk() {
super();
}
/**
* renders a disk on the z = 0 plane. The disk has a radius of
@@ -68,147 +68,135 @@ public class Disk extends Quadric {
* (1, 0.5), at (0, r, 0) it is (0.5, 1), at (-r, 0, 0) it is (0, 0.5), and at
* (0, -r, 0) it is (0.5, 0).
*/
public void draw(float innerRadius, float outerRadius, int slices, int loops)
{
float da, dr;
public void draw(float innerRadius, float outerRadius, int slices, int loops) {
float da, dr;
/* Normal vectors */
if (super.normals != GLU_NONE) {
if (super.orientation == GLU_OUTSIDE) {
glNormal3f(0.0f, 0.0f, +1.0f);
}
else {
glNormal3f(0.0f, 0.0f, -1.0f);
}
}
/* Normal vectors */
if (super.normals != GLU_NONE) {
if (super.orientation == GLU_OUTSIDE) {
glNormal3f(0.0f, 0.0f, +1.0f);
} else {
glNormal3f(0.0f, 0.0f, -1.0f);
}
}
da = 2.0f * PI / slices;
dr = (outerRadius - innerRadius) / loops;
switch (super.drawStyle) {
case GLU_FILL:
{
/* texture of a gluDisk is a cut out of the texture unit square
* x, y in [-outerRadius, +outerRadius]; s, t in [0, 1]
* (linear mapping)
*/
float dtc = 2.0f * outerRadius;
float sa, ca;
float r1 = innerRadius;
int l;
for (l = 0; l < loops; l++) {
float r2 = r1 + dr;
if (super.orientation == GLU_OUTSIDE) {
int s;
glBegin(GL_QUAD_STRIP);
for (s = 0; s <= slices; s++) {
float a;
if (s == slices)
a = 0.0f;
else
a = s * da;
sa = sin(a);
ca = cos(a);
TXTR_COORD(0.5f + sa * r2 / dtc, 0.5f + ca * r2 / dtc);
glVertex2f(r2 * sa, r2 * ca);
TXTR_COORD(0.5f + sa * r1 / dtc, 0.5f + ca * r1 / dtc);
glVertex2f(r1 * sa, r1 * ca);
}
glEnd();
}
else {
int s;
glBegin(GL_QUAD_STRIP);
for (s = slices; s >= 0; s--) {
float a;
if (s == slices)
a = 0.0f;
else
a = s * da;
sa = sin(a);
ca = cos(a);
TXTR_COORD(0.5f - sa * r2 / dtc, 0.5f + ca * r2 / dtc);
glVertex2f(r2 * sa, r2 * ca);
TXTR_COORD(0.5f - sa * r1 / dtc, 0.5f + ca * r1 / dtc);
glVertex2f(r1 * sa, r1 * ca);
}
glEnd();
}
r1 = r2;
}
break;
}
case GLU_LINE:
{
int l, s;
/* draw loops */
for (l = 0; l <= loops; l++) {
float r = innerRadius + l * dr;
glBegin(GL_LINE_LOOP);
for (s = 0; s < slices; s++) {
float a = s * da;
glVertex2f(r * sin(a), r * cos(a));
}
glEnd();
}
/* draw spokes */
for (s = 0; s < slices; s++) {
float a = s * da;
float x = sin(a);
float y = cos(a);
glBegin(GL_LINE_STRIP);
for (l = 0; l <= loops; l++) {
float r = innerRadius + l * dr;
glVertex2f(r * x, r * y);
}
glEnd();
}
break;
}
case GLU_POINT:
{
int s;
glBegin(GL_POINTS);
for (s = 0; s < slices; s++) {
float a = s * da;
float x = sin(a);
float y = cos(a);
int l;
for (l = 0; l <= loops; l++) {
float r = innerRadius * l * dr;
glVertex2f(r * x, r * y);
}
}
glEnd();
break;
}
case GLU_SILHOUETTE:
{
if (innerRadius != 0.0) {
float a;
glBegin(GL_LINE_LOOP);
for (a = 0.0f; a < 2.0 * PI; a += da) {
float x = innerRadius * sin(a);
float y = innerRadius * cos(a);
glVertex2f(x, y);
}
glEnd();
}
{
float a;
glBegin(GL_LINE_LOOP);
for (a = 0; a < 2.0f * PI; a += da) {
float x = outerRadius * sin(a);
float y = outerRadius * cos(a);
glVertex2f(x, y);
}
glEnd();
}
break;
}
default:
return;
}
}
da = 2.0f * PI / slices;
dr = (outerRadius - innerRadius) / loops;
switch (super.drawStyle) {
case GLU_FILL: {
/* texture of a gluDisk is a cut out of the texture unit square
* x, y in [-outerRadius, +outerRadius]; s, t in [0, 1]
* (linear mapping)
*/
float dtc = 2.0f * outerRadius;
float sa, ca;
float r1 = innerRadius;
int l;
for (l = 0; l < loops; l++) {
float r2 = r1 + dr;
if (super.orientation == GLU_OUTSIDE) {
int s;
glBegin(GL_QUAD_STRIP);
for (s = 0; s <= slices; s++) {
float a;
if (s == slices) a = 0.0f;
else a = s * da;
sa = sin(a);
ca = cos(a);
TXTR_COORD(0.5f + sa * r2 / dtc, 0.5f + ca * r2 / dtc);
glVertex2f(r2 * sa, r2 * ca);
TXTR_COORD(0.5f + sa * r1 / dtc, 0.5f + ca * r1 / dtc);
glVertex2f(r1 * sa, r1 * ca);
}
glEnd();
} else {
int s;
glBegin(GL_QUAD_STRIP);
for (s = slices; s >= 0; s--) {
float a;
if (s == slices) a = 0.0f;
else a = s * da;
sa = sin(a);
ca = cos(a);
TXTR_COORD(0.5f - sa * r2 / dtc, 0.5f + ca * r2 / dtc);
glVertex2f(r2 * sa, r2 * ca);
TXTR_COORD(0.5f - sa * r1 / dtc, 0.5f + ca * r1 / dtc);
glVertex2f(r1 * sa, r1 * ca);
}
glEnd();
}
r1 = r2;
}
break;
}
case GLU_LINE: {
int l, s;
/* draw loops */
for (l = 0; l <= loops; l++) {
float r = innerRadius + l * dr;
glBegin(GL_LINE_LOOP);
for (s = 0; s < slices; s++) {
float a = s * da;
glVertex2f(r * sin(a), r * cos(a));
}
glEnd();
}
/* draw spokes */
for (s = 0; s < slices; s++) {
float a = s * da;
float x = sin(a);
float y = cos(a);
glBegin(GL_LINE_STRIP);
for (l = 0; l <= loops; l++) {
float r = innerRadius + l * dr;
glVertex2f(r * x, r * y);
}
glEnd();
}
break;
}
case GLU_POINT: {
int s;
glBegin(GL_POINTS);
for (s = 0; s < slices; s++) {
float a = s * da;
float x = sin(a);
float y = cos(a);
int l;
for (l = 0; l <= loops; l++) {
float r = innerRadius * l * dr;
glVertex2f(r * x, r * y);
}
}
glEnd();
break;
}
case GLU_SILHOUETTE: {
if (innerRadius != 0.0) {
float a;
glBegin(GL_LINE_LOOP);
for (a = 0.0f; a < 2.0 * PI; a += da) {
float x = innerRadius * sin(a);
float y = innerRadius * cos(a);
glVertex2f(x, y);
}
glEnd();
}
{
float a;
glBegin(GL_LINE_LOOP);
for (a = 0; a < 2.0f * PI; a += da) {
float x = outerRadius * sin(a);
float y = outerRadius * cos(a);
glVertex2f(x, y);
}
glEnd();
}
break;
}
default:
return;
}
}
}
+311 -328
View File
@@ -31,14 +31,13 @@
*/
package org.lwjglx.util.glu;
import static org.lwjgl.opengl.GL11.*;
import java.nio.ByteBuffer;
import java.nio.FloatBuffer;
import java.nio.IntBuffer;
import org.lwjglx.util.glu.tessellation.GLUtessellatorImpl;
import org.lwjglx.opengl.Util;
import static org.lwjgl.opengl.GL11.*;
import org.lwjglx.util.glu.tessellation.GLUtessellatorImpl;
/**
* GLU.java
@@ -48,383 +47,367 @@ import static org.lwjgl.opengl.GL11.*;
* @author Erik Duijs
*/
public class GLU {
static final float PI = (float)Math.PI;
static final float PI = (float) Math.PI;
/* Errors: (return value 0 = no error) */
public static final int GLU_INVALID_ENUM = 100900;
public static final int GLU_INVALID_VALUE = 100901;
public static final int GLU_OUT_OF_MEMORY = 100902;
public static final int GLU_INCOMPATIBLE_GL_VERSION = 100903;
/* Errors: (return value 0 = no error) */
public static final int GLU_INVALID_ENUM = 100900;
public static final int GLU_INVALID_VALUE = 100901;
public static final int GLU_OUT_OF_MEMORY = 100902;
public static final int GLU_INCOMPATIBLE_GL_VERSION = 100903;
/* StringName */
public static final int GLU_VERSION = 100800;
public static final int GLU_EXTENSIONS = 100801;
/* StringName */
public static final int GLU_VERSION = 100800;
public static final int GLU_EXTENSIONS = 100801;
/* Boolean */
public static final boolean GLU_TRUE = true;
public static final boolean GLU_FALSE = false;
/* Boolean */
public static final boolean GLU_TRUE = true;
public static final boolean GLU_FALSE = false;
/**** Quadric constants ****/
/**** Quadric constants ****/
/* QuadricNormal */
public static final int GLU_SMOOTH = 100000;
/* QuadricNormal */
public static final int GLU_SMOOTH = 100000;
public static final int GLU_FLAT = 100001;
public static final int GLU_NONE = 100002;
public static final int GLU_FLAT = 100001;
public static final int GLU_NONE = 100002;
/* QuadricDrawStyle */
public static final int GLU_POINT = 100010;
public static final int GLU_LINE = 100011;
public static final int GLU_FILL = 100012;
public static final int GLU_SILHOUETTE = 100013;
/* QuadricDrawStyle */
public static final int GLU_POINT = 100010;
public static final int GLU_LINE = 100011;
public static final int GLU_FILL = 100012;
public static final int GLU_SILHOUETTE = 100013;
/* QuadricOrientation */
public static final int GLU_OUTSIDE = 100020;
public static final int GLU_INSIDE = 100021;
/* QuadricOrientation */
public static final int GLU_OUTSIDE = 100020;
public static final int GLU_INSIDE = 100021;
/* Callback types: */
/* ERROR = 100103 */
/* Callback types: */
/* ERROR = 100103 */
/**** Tesselation constants ****/
public static final double GLU_TESS_MAX_COORD = 1.0e150;
/**** Tesselation constants ****/
public static final double TESS_MAX_COORD = 1.0e150;
public static final double GLU_TESS_MAX_COORD = 1.0e150;
public static final double TESS_MAX_COORD = 1.0e150;
/* TessProperty */
public static final int GLU_TESS_WINDING_RULE = 100140;
public static final int GLU_TESS_BOUNDARY_ONLY = 100141;
public static final int GLU_TESS_TOLERANCE = 100142;
/* TessProperty */
public static final int GLU_TESS_WINDING_RULE = 100140;
public static final int GLU_TESS_BOUNDARY_ONLY = 100141;
public static final int GLU_TESS_TOLERANCE = 100142;
/* TessWinding */
public static final int GLU_TESS_WINDING_ODD = 100130;
public static final int GLU_TESS_WINDING_NONZERO = 100131;
public static final int GLU_TESS_WINDING_POSITIVE = 100132;
public static final int GLU_TESS_WINDING_NEGATIVE = 100133;
public static final int GLU_TESS_WINDING_ABS_GEQ_TWO = 100134;
/* TessWinding */
public static final int GLU_TESS_WINDING_ODD = 100130;
public static final int GLU_TESS_WINDING_NONZERO = 100131;
public static final int GLU_TESS_WINDING_POSITIVE = 100132;
public static final int GLU_TESS_WINDING_NEGATIVE = 100133;
public static final int GLU_TESS_WINDING_ABS_GEQ_TWO = 100134;
/* TessCallback */
public static final int GLU_TESS_BEGIN = 100100; /* void (CALLBACK*)(GLenum type) */
public static final int GLU_TESS_VERTEX = 100101; /* void (CALLBACK*)(void *data) */
public static final int GLU_TESS_END = 100102; /* void (CALLBACK*)(void) */
public static final int GLU_TESS_ERROR = 100103; /* void (CALLBACK*)(GLenum errno) */
public static final int GLU_TESS_EDGE_FLAG = 100104; /* void (CALLBACK*)(GLboolean boundaryEdge) */
public static final int GLU_TESS_COMBINE = 100105; /* void (CALLBACK*)(GLdouble coords[3],
/* TessCallback */
public static final int GLU_TESS_BEGIN = 100100; /* void (CALLBACK*)(GLenum type) */
public static final int GLU_TESS_VERTEX = 100101; /* void (CALLBACK*)(void *data) */
public static final int GLU_TESS_END = 100102; /* void (CALLBACK*)(void) */
public static final int GLU_TESS_ERROR = 100103; /* void (CALLBACK*)(GLenum errno) */
public static final int GLU_TESS_EDGE_FLAG = 100104; /* void (CALLBACK*)(GLboolean boundaryEdge) */
public static final int GLU_TESS_COMBINE = 100105; /* void (CALLBACK*)(GLdouble coords[3],
void *data[4],
GLfloat weight[4],
void **dataOut) */
public static final int GLU_TESS_BEGIN_DATA = 100106; /* void (CALLBACK*)(GLenum type,
public static final int GLU_TESS_BEGIN_DATA = 100106; /* void (CALLBACK*)(GLenum type,
void *polygon_data) */
public static final int GLU_TESS_VERTEX_DATA = 100107; /* void (CALLBACK*)(void *data,
public static final int GLU_TESS_VERTEX_DATA = 100107; /* void (CALLBACK*)(void *data,
void *polygon_data) */
public static final int GLU_TESS_END_DATA = 100108; /* void (CALLBACK*)(void *polygon_data) */
public static final int GLU_TESS_ERROR_DATA = 100109; /* void (CALLBACK*)(GLenum errno,
public static final int GLU_TESS_END_DATA = 100108; /* void (CALLBACK*)(void *polygon_data) */
public static final int GLU_TESS_ERROR_DATA = 100109; /* void (CALLBACK*)(GLenum errno,
void *polygon_data) */
public static final int GLU_TESS_EDGE_FLAG_DATA = 100110; /* void (CALLBACK*)(GLboolean boundaryEdge,
public static final int GLU_TESS_EDGE_FLAG_DATA = 100110; /* void (CALLBACK*)(GLboolean boundaryEdge,
void *polygon_data) */
public static final int GLU_TESS_COMBINE_DATA = 100111; /* void (CALLBACK*)(GLdouble coords[3],
public static final int GLU_TESS_COMBINE_DATA = 100111; /* void (CALLBACK*)(GLdouble coords[3],
void *data[4],
GLfloat weight[4],
void **dataOut,
void *polygon_data) */
/* TessError */
public static final int GLU_TESS_ERROR1 = 100151;
public static final int GLU_TESS_ERROR2 = 100152;
public static final int GLU_TESS_ERROR3 = 100153;
public static final int GLU_TESS_ERROR4 = 100154;
public static final int GLU_TESS_ERROR5 = 100155;
public static final int GLU_TESS_ERROR6 = 100156;
public static final int GLU_TESS_ERROR7 = 100157;
public static final int GLU_TESS_ERROR8 = 100158;
/* TessError */
public static final int GLU_TESS_ERROR1 = 100151;
public static final int GLU_TESS_ERROR2 = 100152;
public static final int GLU_TESS_ERROR3 = 100153;
public static final int GLU_TESS_ERROR4 = 100154;
public static final int GLU_TESS_ERROR5 = 100155;
public static final int GLU_TESS_ERROR6 = 100156;
public static final int GLU_TESS_ERROR7 = 100157;
public static final int GLU_TESS_ERROR8 = 100158;
public static final int GLU_TESS_MISSING_BEGIN_POLYGON = GLU_TESS_ERROR1;
public static final int GLU_TESS_MISSING_BEGIN_CONTOUR = GLU_TESS_ERROR2;
public static final int GLU_TESS_MISSING_END_POLYGON = GLU_TESS_ERROR3;
public static final int GLU_TESS_MISSING_END_CONTOUR = GLU_TESS_ERROR4;
public static final int GLU_TESS_COORD_TOO_LARGE = GLU_TESS_ERROR5;
public static final int GLU_TESS_NEED_COMBINE_CALLBACK = GLU_TESS_ERROR6;
public static final int GLU_TESS_MISSING_BEGIN_POLYGON = GLU_TESS_ERROR1;
public static final int GLU_TESS_MISSING_BEGIN_CONTOUR = GLU_TESS_ERROR2;
public static final int GLU_TESS_MISSING_END_POLYGON = GLU_TESS_ERROR3;
public static final int GLU_TESS_MISSING_END_CONTOUR = GLU_TESS_ERROR4;
public static final int GLU_TESS_COORD_TOO_LARGE = GLU_TESS_ERROR5;
public static final int GLU_TESS_NEED_COMBINE_CALLBACK = GLU_TESS_ERROR6;
/**** NURBS constants ****/
/**** NURBS constants ****/
/* NurbsProperty */
public static final int GLU_AUTO_LOAD_MATRIX = 100200;
public static final int GLU_CULLING = 100201;
public static final int GLU_SAMPLING_TOLERANCE = 100203;
public static final int GLU_DISPLAY_MODE = 100204;
public static final int GLU_PARAMETRIC_TOLERANCE = 100202;
public static final int GLU_SAMPLING_METHOD = 100205;
public static final int GLU_U_STEP = 100206;
public static final int GLU_V_STEP = 100207;
/* NurbsProperty */
public static final int GLU_AUTO_LOAD_MATRIX = 100200;
/* NurbsSampling */
public static final int GLU_PATH_LENGTH = 100215;
public static final int GLU_PARAMETRIC_ERROR = 100216;
public static final int GLU_DOMAIN_DISTANCE = 100217;
public static final int GLU_CULLING = 100201;
public static final int GLU_SAMPLING_TOLERANCE = 100203;
public static final int GLU_DISPLAY_MODE = 100204;
public static final int GLU_PARAMETRIC_TOLERANCE = 100202;
public static final int GLU_SAMPLING_METHOD = 100205;
public static final int GLU_U_STEP = 100206;
public static final int GLU_V_STEP = 100207;
/* NurbsSampling */
public static final int GLU_PATH_LENGTH = 100215;
public static final int GLU_PARAMETRIC_ERROR = 100216;
public static final int GLU_DOMAIN_DISTANCE = 100217;
/* NurbsTrim */
public static final int GLU_MAP1_TRIM_2 = 100210;
public static final int GLU_MAP1_TRIM_3 = 100211;
/* NurbsTrim */
public static final int GLU_MAP1_TRIM_2 = 100210;
public static final int GLU_MAP1_TRIM_3 = 100211;
/* NurbsDisplay */
/* FILL = 100012 */
public static final int GLU_OUTLINE_POLYGON = 100240;
public static final int GLU_OUTLINE_PATCH = 100241;
/* NurbsDisplay */
/* FILL = 100012 */
public static final int GLU_OUTLINE_POLYGON = 100240;
public static final int GLU_OUTLINE_PATCH = 100241;
/* NurbsCallback */
/* ERROR = 100103 */
/* NurbsCallback */
/* ERROR = 100103 */
/* NurbsErrors */
public static final int GLU_NURBS_ERROR1 = 100251;
public static final int GLU_NURBS_ERROR2 = 100252;
public static final int GLU_NURBS_ERROR3 = 100253;
public static final int GLU_NURBS_ERROR4 = 100254;
public static final int GLU_NURBS_ERROR5 = 100255;
public static final int GLU_NURBS_ERROR6 = 100256;
public static final int GLU_NURBS_ERROR7 = 100257;
public static final int GLU_NURBS_ERROR8 = 100258;
public static final int GLU_NURBS_ERROR9 = 100259;
public static final int GLU_NURBS_ERROR10 = 100260;
public static final int GLU_NURBS_ERROR11 = 100261;
public static final int GLU_NURBS_ERROR12 = 100262;
public static final int GLU_NURBS_ERROR13 = 100263;
public static final int GLU_NURBS_ERROR14 = 100264;
public static final int GLU_NURBS_ERROR15 = 100265;
public static final int GLU_NURBS_ERROR16 = 100266;
public static final int GLU_NURBS_ERROR17 = 100267;
public static final int GLU_NURBS_ERROR18 = 100268;
public static final int GLU_NURBS_ERROR19 = 100269;
public static final int GLU_NURBS_ERROR20 = 100270;
public static final int GLU_NURBS_ERROR21 = 100271;
public static final int GLU_NURBS_ERROR22 = 100272;
public static final int GLU_NURBS_ERROR23 = 100273;
public static final int GLU_NURBS_ERROR24 = 100274;
public static final int GLU_NURBS_ERROR25 = 100275;
public static final int GLU_NURBS_ERROR26 = 100276;
public static final int GLU_NURBS_ERROR27 = 100277;
public static final int GLU_NURBS_ERROR28 = 100278;
public static final int GLU_NURBS_ERROR29 = 100279;
public static final int GLU_NURBS_ERROR30 = 100280;
public static final int GLU_NURBS_ERROR31 = 100281;
public static final int GLU_NURBS_ERROR32 = 100282;
public static final int GLU_NURBS_ERROR33 = 100283;
public static final int GLU_NURBS_ERROR34 = 100284;
public static final int GLU_NURBS_ERROR35 = 100285;
public static final int GLU_NURBS_ERROR36 = 100286;
public static final int GLU_NURBS_ERROR37 = 100287;
/* NurbsErrors */
public static final int GLU_NURBS_ERROR1 = 100251;
public static final int GLU_NURBS_ERROR2 = 100252;
public static final int GLU_NURBS_ERROR3 = 100253;
public static final int GLU_NURBS_ERROR4 = 100254;
public static final int GLU_NURBS_ERROR5 = 100255;
public static final int GLU_NURBS_ERROR6 = 100256;
public static final int GLU_NURBS_ERROR7 = 100257;
public static final int GLU_NURBS_ERROR8 = 100258;
public static final int GLU_NURBS_ERROR9 = 100259;
public static final int GLU_NURBS_ERROR10 = 100260;
public static final int GLU_NURBS_ERROR11 = 100261;
public static final int GLU_NURBS_ERROR12 = 100262;
public static final int GLU_NURBS_ERROR13 = 100263;
public static final int GLU_NURBS_ERROR14 = 100264;
public static final int GLU_NURBS_ERROR15 = 100265;
public static final int GLU_NURBS_ERROR16 = 100266;
public static final int GLU_NURBS_ERROR17 = 100267;
public static final int GLU_NURBS_ERROR18 = 100268;
public static final int GLU_NURBS_ERROR19 = 100269;
public static final int GLU_NURBS_ERROR20 = 100270;
public static final int GLU_NURBS_ERROR21 = 100271;
public static final int GLU_NURBS_ERROR22 = 100272;
public static final int GLU_NURBS_ERROR23 = 100273;
public static final int GLU_NURBS_ERROR24 = 100274;
public static final int GLU_NURBS_ERROR25 = 100275;
public static final int GLU_NURBS_ERROR26 = 100276;
public static final int GLU_NURBS_ERROR27 = 100277;
public static final int GLU_NURBS_ERROR28 = 100278;
public static final int GLU_NURBS_ERROR29 = 100279;
public static final int GLU_NURBS_ERROR30 = 100280;
public static final int GLU_NURBS_ERROR31 = 100281;
public static final int GLU_NURBS_ERROR32 = 100282;
public static final int GLU_NURBS_ERROR33 = 100283;
public static final int GLU_NURBS_ERROR34 = 100284;
public static final int GLU_NURBS_ERROR35 = 100285;
public static final int GLU_NURBS_ERROR36 = 100286;
public static final int GLU_NURBS_ERROR37 = 100287;
/* Contours types -- obsolete! */
public static final int GLU_CW = 100120;
public static final int GLU_CCW = 100121;
public static final int GLU_INTERIOR = 100122;
public static final int GLU_EXTERIOR = 100123;
public static final int GLU_UNKNOWN = 100124;
/* Contours types -- obsolete! */
public static final int GLU_CW = 100120;
public static final int GLU_CCW = 100121;
public static final int GLU_INTERIOR = 100122;
public static final int GLU_EXTERIOR = 100123;
public static final int GLU_UNKNOWN = 100124;
/* Names without "TESS_" prefix */
public static final int GLU_BEGIN = GLU_TESS_BEGIN;
public static final int GLU_VERTEX = GLU_TESS_VERTEX;
public static final int GLU_END = GLU_TESS_END;
public static final int GLU_ERROR = GLU_TESS_ERROR;
public static final int GLU_EDGE_FLAG = GLU_TESS_EDGE_FLAG;
/* Names without "TESS_" prefix */
public static final int GLU_BEGIN = GLU_TESS_BEGIN;
public static final int GLU_VERTEX = GLU_TESS_VERTEX;
public static final int GLU_END = GLU_TESS_END;
public static final int GLU_ERROR = GLU_TESS_ERROR;
public static final int GLU_EDGE_FLAG = GLU_TESS_EDGE_FLAG;
/**
* Method gluLookAt
* @param eyex
* @param eyey
* @param eyez
* @param centerx
* @param centery
* @param centerz
* @param upx
* @param upy
* @param upz
*/
public static void gluLookAt(
float eyex,
float eyey,
float eyez,
float centerx,
float centery,
float centerz,
float upx,
float upy,
float upz) {
/**
* Method gluLookAt
* @param eyex
* @param eyey
* @param eyez
* @param centerx
* @param centery
* @param centerz
* @param upx
* @param upy
* @param upz
*/
public static void gluLookAt(
float eyex,
float eyey,
float eyez,
float centerx,
float centery,
float centerz,
float upx,
float upy,
float upz) {
Project.gluLookAt(eyex, eyey, eyez, centerx, centery, centerz, upx, upy, upz);
}
Project.gluLookAt(eyex, eyey, eyez, centerx, centery, centerz, upx, upy, upz);
}
/**
* Method gluOrtho2D
* @param left
* @param right
* @param bottom
* @param top
*/
public static void gluOrtho2D(
float left,
float right,
float bottom,
float top) {
/**
* Method gluOrtho2D
* @param left
* @param right
* @param bottom
* @param top
*/
public static void gluOrtho2D(float left, float right, float bottom, float top) {
glOrtho(left, right, bottom, top, -1.0, 1.0);
}
glOrtho(left, right, bottom, top, -1.0, 1.0);
}
/**
* Method gluPerspective
* @param fovy
* @param aspect
* @param zNear
* @param zFar
*/
public static void gluPerspective(
float fovy,
float aspect,
float zNear,
float zFar) {
/**
* Method gluPerspective
* @param fovy
* @param aspect
* @param zNear
* @param zFar
*/
public static void gluPerspective(float fovy, float aspect, float zNear, float zFar) {
Project.gluPerspective(fovy, aspect, zNear, zFar);
}
Project.gluPerspective(fovy, aspect, zNear, zFar);
}
/**
* Method gluProject
* @param objx
* @param objy
* @param objz
* @param modelMatrix
* @param projMatrix
* @param viewport
* @param win_pos
*/
public static boolean gluProject(float objx, float objy, float objz,
FloatBuffer modelMatrix,
FloatBuffer projMatrix,
IntBuffer viewport,
FloatBuffer win_pos)
{
return Project.gluProject(objx, objy, objz, modelMatrix, projMatrix, viewport, win_pos);
}
/**
* Method gluProject
* @param objx
* @param objy
* @param objz
* @param modelMatrix
* @param projMatrix
* @param viewport
* @param win_pos
*/
public static boolean gluProject(
float objx,
float objy,
float objz,
FloatBuffer modelMatrix,
FloatBuffer projMatrix,
IntBuffer viewport,
FloatBuffer win_pos) {
return Project.gluProject(objx, objy, objz, modelMatrix, projMatrix, viewport, win_pos);
}
/**
* Method gluUnproject
* @param winx
* @param winy
* @param winz
* @param modelMatrix
* @param projMatrix
* @param viewport
* @param obj_pos
*/
public static boolean gluUnProject(float winx, float winy, float winz,
FloatBuffer modelMatrix,
FloatBuffer projMatrix,
IntBuffer viewport,
FloatBuffer obj_pos)
{
return Project.gluUnProject(winx, winy, winz, modelMatrix, projMatrix, viewport, obj_pos);
}
/**
* Method gluUnproject
* @param winx
* @param winy
* @param winz
* @param modelMatrix
* @param projMatrix
* @param viewport
* @param obj_pos
*/
public static boolean gluUnProject(
float winx,
float winy,
float winz,
FloatBuffer modelMatrix,
FloatBuffer projMatrix,
IntBuffer viewport,
FloatBuffer obj_pos) {
return Project.gluUnProject(winx, winy, winz, modelMatrix, projMatrix, viewport, obj_pos);
}
/**
* Method gluPickMatrix
* @param x
* @param y
* @param width
* @param height
* @param viewport
*/
public static void gluPickMatrix(
float x,
float y,
float width,
float height,
IntBuffer viewport) {
/**
* Method gluPickMatrix
* @param x
* @param y
* @param width
* @param height
* @param viewport
*/
public static void gluPickMatrix(float x, float y, float width, float height, IntBuffer viewport) {
Project.gluPickMatrix(x, y, width, height, viewport);
}
Project.gluPickMatrix(x, y, width, height, viewport);
}
/**
* Method gluGetString.
* @param name
* @return String
*/
public static String gluGetString(int name) {
return Registry.gluGetString(name);
}
/**
* Method gluGetString.
* @param name
* @return String
*/
public static String gluGetString(int name) {
return Registry.gluGetString(name);
}
/**
* Method gluCheckExtension.
* @param extName
* @param extString
* @return boolean
*/
public static boolean gluCheckExtension(String extName, String extString) {
return Registry.gluCheckExtension(extName, extString);
}
/**
* Method gluCheckExtension.
* @param extName
* @param extString
* @return boolean
*/
public static boolean gluCheckExtension(String extName, String extString) {
return Registry.gluCheckExtension(extName, extString);
}
/**
* Method gluBuild2DMipmaps
* @param target
* @param components
* @param width
* @param height
* @param format
* @param type
* @param data
* @return int
*/
public static int gluBuild2DMipmaps(
int target,
int components,
int width,
int height,
int format,
int type,
ByteBuffer data) {
/**
* Method gluBuild2DMipmaps
* @param target
* @param components
* @param width
* @param height
* @param format
* @param type
* @param data
* @return int
*/
public static int gluBuild2DMipmaps(
int target, int components, int width, int height, int format, int type, ByteBuffer data) {
return MipMap.gluBuild2DMipmaps(target, components, width, height, format, type, data);
}
return MipMap.gluBuild2DMipmaps(target, components, width, height, format, type, data);
}
/**
* Method gluScaleImage.
* @param format
* @param widthIn
* @param heightIn
* @param typeIn
* @param dataIn
* @param widthOut
* @param heightOut
* @param typeOut
* @param dataOut
* @return int
*/
public static int gluScaleImage(
int format,
int widthIn,
int heightIn,
int typeIn,
ByteBuffer dataIn,
int widthOut,
int heightOut,
int typeOut,
ByteBuffer dataOut) {
/**
* Method gluScaleImage.
* @param format
* @param widthIn
* @param heightIn
* @param typeIn
* @param dataIn
* @param widthOut
* @param heightOut
* @param typeOut
* @param dataOut
* @return int
*/
public static int gluScaleImage(
int format,
int widthIn,
int heightIn,
int typeIn,
ByteBuffer dataIn,
int widthOut,
int heightOut,
int typeOut,
ByteBuffer dataOut) {
return MipMap.gluScaleImage(format, widthIn, heightIn, typeIn, dataIn, widthOut, heightOut, typeOut, dataOut);
}
return MipMap.gluScaleImage(format, widthIn, heightIn, typeIn, dataIn, widthOut, heightOut, typeOut, dataOut);
}
public static String gluErrorString(int error_code) {
switch (error_code) {
case GLU_INVALID_ENUM:
return "Invalid enum (glu)";
case GLU_INVALID_VALUE:
return "Invalid value (glu)";
case GLU_OUT_OF_MEMORY:
return "Out of memory (glu)";
default:
return Util.translateGLErrorString(error_code);
}
}
public static String gluErrorString(int error_code) {
switch (error_code) {
case GLU_INVALID_ENUM:
return "Invalid enum (glu)";
case GLU_INVALID_VALUE:
return "Invalid value (glu)";
case GLU_OUT_OF_MEMORY:
return "Out of memory (glu)";
default:
return Util.translateGLErrorString(error_code);
}
}
public static GLUtessellator gluNewTess() {
return new GLUtessellatorImpl();
}
public static GLUtessellator gluNewTess() {
return new GLUtessellatorImpl();
}
}
@@ -34,39 +34,35 @@ package org.lwjglx.util.glu;
public interface GLUtessellator {
void gluDeleteTess();
void gluDeleteTess();
void gluTessProperty(int which, double value);
void gluTessProperty(int which, double value);
/* Returns tessellator property */
void gluGetTessProperty(int which, double[] value,
int value_offset); /* gluGetTessProperty() */
/* Returns tessellator property */
void gluGetTessProperty(int which, double[] value, int value_offset); /* gluGetTessProperty() */
void gluTessNormal(double x, double y, double z);
void gluTessNormal(double x, double y, double z);
void gluTessCallback(int which,
GLUtessellatorCallback aCallback);
void gluTessCallback(int which, GLUtessellatorCallback aCallback);
void gluTessVertex(double[] coords, int coords_offset,
Object vertexData);
void gluTessVertex(double[] coords, int coords_offset, Object vertexData);
void gluTessBeginPolygon(Object data);
void gluTessBeginPolygon(Object data);
void gluTessBeginContour();
void gluTessBeginContour();
void gluTessEndContour();
void gluTessEndContour();
void gluTessEndPolygon();
void gluTessEndPolygon();
/*******************************************************/
/*******************************************************/
/* Obsolete calls -- for backward compatibility */
/* Obsolete calls -- for backward compatibility */
void gluBeginPolygon();
void gluBeginPolygon();
/*ARGSUSED*/
void gluNextContour(int type);
/*ARGSUSED*/
void gluNextContour(int type);
void gluEndPolygon();
}
void gluEndPolygon();
}
@@ -31,57 +31,57 @@
*/
/*
* Portions Copyright (C) 2003-2006 Sun Microsystems, Inc.
* All rights reserved.
*/
* Portions Copyright (C) 2003-2006 Sun Microsystems, Inc.
* All rights reserved.
*/
/*
** License Applicability. Except to the extent portions of this file are
** made subject to an alternative license as permitted in the SGI Free
** Software License B, Version 1.1 (the "License"), the contents of this
** file are subject only to the provisions of the License. You may not use
** this file except in compliance with the License. You may obtain a copy
** of the License at Silicon Graphics, Inc., attn: Legal Services, 1600
** Amphitheatre Parkway, Mountain View, CA 94043-1351, or at:
**
** http://oss.sgi.com/projects/FreeB
**
** Note that, as provided in the License, the Software is distributed on an
** "AS IS" basis, with ALL EXPRESS AND IMPLIED WARRANTIES AND CONDITIONS
** DISCLAIMED, INCLUDING, WITHOUT LIMITATION, ANY IMPLIED WARRANTIES AND
** CONDITIONS OF MERCHANTABILITY, SATISFACTORY QUALITY, FITNESS FOR A
** PARTICULAR PURPOSE, AND NON-INFRINGEMENT.
**
** NOTE: The Original Code (as defined below) has been licensed to Sun
** Microsystems, Inc. ("Sun") under the SGI Free Software License B
** (Version 1.1), shown above ("SGI License"). Pursuant to Section
** 3.2(3) of the SGI License, Sun is distributing the Covered Code to
** you under an alternative license ("Alternative License"). This
** Alternative License includes all of the provisions of the SGI License
** except that Section 2.2 and 11 are omitted. Any differences between
** the Alternative License and the SGI License are offered solely by Sun
** and not by SGI.
**
** Original Code. The Original Code is: OpenGL Sample Implementation,
** Version 1.2.1, released January 26, 2000, developed by Silicon Graphics,
** Inc. The Original Code is Copyright (c) 1991-2000 Silicon Graphics, Inc.
** Copyright in any portions created by third parties is as indicated
** elsewhere herein. All Rights Reserved.
**
** Additional Notice Provisions: The application programming interfaces
** established by SGI in conjunction with the Original Code are The
** OpenGL(R) Graphics System: A Specification (Version 1.2.1), released
** April 1, 1999; The OpenGL(R) Graphics System Utility Library (Version
** 1.3), released November 4, 1998; and OpenGL(R) Graphics with the X
** Window System(R) (Version 1.3), released October 19, 1998. This software
** was created using the OpenGL(R) version 1.2.1 Sample Implementation
** published by SGI, but has not been independently verified as being
** compliant with the OpenGL(R) version 1.2.1 Specification.
**
** Author: Eric Veach, July 1994
** Java Port: Pepijn Van Eeckhoudt, July 2003
** Java Port: Nathan Parker Burg, August 2003
*/
** License Applicability. Except to the extent portions of this file are
** made subject to an alternative license as permitted in the SGI Free
** Software License B, Version 1.1 (the "License"), the contents of this
** file are subject only to the provisions of the License. You may not use
** this file except in compliance with the License. You may obtain a copy
** of the License at Silicon Graphics, Inc., attn: Legal Services, 1600
** Amphitheatre Parkway, Mountain View, CA 94043-1351, or at:
**
** http://oss.sgi.com/projects/FreeB
**
** Note that, as provided in the License, the Software is distributed on an
** "AS IS" basis, with ALL EXPRESS AND IMPLIED WARRANTIES AND CONDITIONS
** DISCLAIMED, INCLUDING, WITHOUT LIMITATION, ANY IMPLIED WARRANTIES AND
** CONDITIONS OF MERCHANTABILITY, SATISFACTORY QUALITY, FITNESS FOR A
** PARTICULAR PURPOSE, AND NON-INFRINGEMENT.
**
** NOTE: The Original Code (as defined below) has been licensed to Sun
** Microsystems, Inc. ("Sun") under the SGI Free Software License B
** (Version 1.1), shown above ("SGI License"). Pursuant to Section
** 3.2(3) of the SGI License, Sun is distributing the Covered Code to
** you under an alternative license ("Alternative License"). This
** Alternative License includes all of the provisions of the SGI License
** except that Section 2.2 and 11 are omitted. Any differences between
** the Alternative License and the SGI License are offered solely by Sun
** and not by SGI.
**
** Original Code. The Original Code is: OpenGL Sample Implementation,
** Version 1.2.1, released January 26, 2000, developed by Silicon Graphics,
** Inc. The Original Code is Copyright (c) 1991-2000 Silicon Graphics, Inc.
** Copyright in any portions created by third parties is as indicated
** elsewhere herein. All Rights Reserved.
**
** Additional Notice Provisions: The application programming interfaces
** established by SGI in conjunction with the Original Code are The
** OpenGL(R) Graphics System: A Specification (Version 1.2.1), released
** April 1, 1999; The OpenGL(R) Graphics System Utility Library (Version
** 1.3), released November 4, 1998; and OpenGL(R) Graphics with the X
** Window System(R) (Version 1.3), released October 19, 1998. This software
** was created using the OpenGL(R) version 1.2.1 Sample Implementation
** published by SGI, but has not been independently verified as being
** compliant with the OpenGL(R) version 1.2.1 Specification.
**
** Author: Eric Veach, July 1994
** Java Port: Pepijn Van Eeckhoudt, July 2003
** Java Port: Nathan Parker Burg, August 2003
*/
package org.lwjglx.util.glu;
/**
@@ -93,296 +93,283 @@ package org.lwjglx.util.glu;
* @author Java Port: Nathan Parker Burg, August 2003
*/
public interface GLUtessellatorCallback {
/**
* The <b>begin</b> callback method is invoked like
* {@link javax.media.opengl.GL#glBegin glBegin} to indicate the start of a
* (triangle) primitive. The method takes a single argument of type int. If
* the <b>GLU_TESS_BOUNDARY_ONLY</b> property is set to <b>GL_FALSE</b>, then
* the argument is set to either <b>GL_TRIANGLE_FAN</b>,
* <b>GL_TRIANGLE_STRIP</b>, or <b>GL_TRIANGLES</b>. If the
* <b>GLU_TESS_BOUNDARY_ONLY</b> property is set to <b>GL_TRUE</b>, then the
* argument will be set to <b>GL_LINE_LOOP</b>.
*
* @param type
* Specifics the type of begin/end pair being defined. The following
* values are valid: <b>GL_TRIANGLE_FAN</b>, <b>GL_TRIANGLE_STRIP</b>,
* <b>GL_TRIANGLES</b> or <b>GL_LINE_LOOP</b>.
*
* @see GLU#gluTessCallback gluTessCallback
* @see #end end
* @see #begin begin
*/
void begin(int type);
/**
* The <b>begin</b> callback method is invoked like
* {@link javax.media.opengl.GL#glBegin glBegin} to indicate the start of a
* (triangle) primitive. The method takes a single argument of type int. If
* the <b>GLU_TESS_BOUNDARY_ONLY</b> property is set to <b>GL_FALSE</b>, then
* the argument is set to either <b>GL_TRIANGLE_FAN</b>,
* <b>GL_TRIANGLE_STRIP</b>, or <b>GL_TRIANGLES</b>. If the
* <b>GLU_TESS_BOUNDARY_ONLY</b> property is set to <b>GL_TRUE</b>, then the
* argument will be set to <b>GL_LINE_LOOP</b>.
*
* @param type
* Specifics the type of begin/end pair being defined. The following
* values are valid: <b>GL_TRIANGLE_FAN</b>, <b>GL_TRIANGLE_STRIP</b>,
* <b>GL_TRIANGLES</b> or <b>GL_LINE_LOOP</b>.
*
* @see GLU#gluTessCallback gluTessCallback
* @see #end end
* @see #begin begin
*/
void begin(int type);
/**
* The same as the {@link #begin begin} callback method except that
* it takes an additional reference argument. This reference is
* identical to the opaque reference provided when {@link
* GLU#gluTessBeginPolygon gluTessBeginPolygon} was called.
*
* @param type
* Specifics the type of begin/end pair being defined. The following
* values are valid: <b>GL_TRIANGLE_FAN</b>, <b>GL_TRIANGLE_STRIP</b>,
* <b>GL_TRIANGLES</b> or <b>GL_LINE_LOOP</b>.
* @param polygonData
* Specifics a reference to user-defined data.
*
* @see GLU#gluTessCallback gluTessCallback
* @see #endData endData
* @see #begin begin
*/
void beginData(int type, Object polygonData);
/**
* The same as the {@link #begin begin} callback method except that
* it takes an additional reference argument. This reference is
* identical to the opaque reference provided when {@link
* GLU#gluTessBeginPolygon gluTessBeginPolygon} was called.
*
* @param type
* Specifics the type of begin/end pair being defined. The following
* values are valid: <b>GL_TRIANGLE_FAN</b>, <b>GL_TRIANGLE_STRIP</b>,
* <b>GL_TRIANGLES</b> or <b>GL_LINE_LOOP</b>.
* @param polygonData
* Specifics a reference to user-defined data.
*
* @see GLU#gluTessCallback gluTessCallback
* @see #endData endData
* @see #begin begin
*/
void beginData(int type, Object polygonData);
/**
* The <b>edgeFlag</b> callback method is similar to
* {@link javax.media.opengl.GL#glEdgeFlag glEdgeFlag}. The method takes
* a single boolean boundaryEdge that indicates which edges lie on the
* polygon boundary. If the boundaryEdge is <b>GL_TRUE</b>, then each vertex
* that follows begins an edge that lies on the polygon boundary, that is,
* an edge that separates an interior region from an exterior one. If the
* boundaryEdge is <b>GL_FALSE</b>, then each vertex that follows begins an
* edge that lies in the polygon interior. The edge flag callback (if
* defined) is invoked before the first vertex callback.<P>
*
* Since triangle fans and triangle strips do not support edge flags, the
* begin callback is not called with <b>GL_TRIANGLE_FAN</b> or
* <b>GL_TRIANGLE_STRIP</b> if a non-null edge flag callback is provided.
* (If the callback is initialized to null, there is no impact on
* performance). Instead, the fans and strips are converted to independent
* triangles.
*
* @param boundaryEdge
* Specifics which edges lie on the polygon boundary.
*
* @see GLU#gluTessCallback gluTessCallback
* @see #edgeFlagData edgeFlagData
*/
void edgeFlag(boolean boundaryEdge);
/**
* The <b>edgeFlag</b> callback method is similar to
* {@link javax.media.opengl.GL#glEdgeFlag glEdgeFlag}. The method takes
* a single boolean boundaryEdge that indicates which edges lie on the
* polygon boundary. If the boundaryEdge is <b>GL_TRUE</b>, then each vertex
* that follows begins an edge that lies on the polygon boundary, that is,
* an edge that separates an interior region from an exterior one. If the
* boundaryEdge is <b>GL_FALSE</b>, then each vertex that follows begins an
* edge that lies in the polygon interior. The edge flag callback (if
* defined) is invoked before the first vertex callback.<P>
*
* Since triangle fans and triangle strips do not support edge flags, the
* begin callback is not called with <b>GL_TRIANGLE_FAN</b> or
* <b>GL_TRIANGLE_STRIP</b> if a non-null edge flag callback is provided.
* (If the callback is initialized to null, there is no impact on
* performance). Instead, the fans and strips are converted to independent
* triangles.
*
* @param boundaryEdge
* Specifics which edges lie on the polygon boundary.
*
* @see GLU#gluTessCallback gluTessCallback
* @see #edgeFlagData edgeFlagData
*/
void edgeFlag(boolean boundaryEdge);
/**
* The same as the {@link #edgeFlag edgeFlage} callback method
* except that it takes an additional reference argument. This
* reference is identical to the opaque reference provided when
* {@link GLU#gluTessBeginPolygon gluTessBeginPolygon} was called.
*
* @param boundaryEdge
* Specifics which edges lie on the polygon boundary.
* @param polygonData
* Specifics a reference to user-defined data.
*
* @see GLU#gluTessCallback gluTessCallback
* @see #edgeFlag edgeFlag
*/
void edgeFlagData(boolean boundaryEdge, Object polygonData);
/**
* The <b>vertex</b> callback method is invoked between the {@link
* #begin begin} and {@link #end end} callback methods. It is
* similar to {@link javax.media.opengl.GL#glVertex3f glVertex3f},
* and it defines the vertices of the triangles created by the
* tessellation process. The method takes a reference as its only
* argument. This reference is identical to the opaque reference
* provided by the user when the vertex was described (see {@link
* GLU#gluTessVertex gluTessVertex}).
*
* @param vertexData
* Specifics a reference to the vertices of the triangles created
* byt the tessellatin process.
*
* @see GLU#gluTessCallback gluTessCallback
* @see #vertexData vertexData
*/
void vertex(Object vertexData);
/**
* The same as the {@link #edgeFlag edgeFlage} callback method
* except that it takes an additional reference argument. This
* reference is identical to the opaque reference provided when
* {@link GLU#gluTessBeginPolygon gluTessBeginPolygon} was called.
*
* @param boundaryEdge
* Specifics which edges lie on the polygon boundary.
* @param polygonData
* Specifics a reference to user-defined data.
*
* @see GLU#gluTessCallback gluTessCallback
* @see #edgeFlag edgeFlag
*/
void edgeFlagData(boolean boundaryEdge, Object polygonData);
/**
* The same as the {@link #vertex vertex} callback method except
* that it takes an additional reference argument. This reference is
* identical to the opaque reference provided when {@link
* GLU#gluTessBeginPolygon gluTessBeginPolygon} was called.
*
* @param vertexData
* Specifics a reference to the vertices of the triangles created
* byt the tessellatin process.
* @param polygonData
* Specifics a reference to user-defined data.
*
* @see GLU#gluTessCallback gluTessCallback
* @see #vertex vertex
*/
void vertexData(Object vertexData, Object polygonData);
/**
* The end callback serves the same purpose as
* {@link javax.media.opengl.GL#glEnd glEnd}. It indicates the end of a
* primitive and it takes no arguments.
*
* @see GLU#gluTessCallback gluTessCallback
* @see #begin begin
* @see #endData endData
*/
void end();
/**
* The <b>vertex</b> callback method is invoked between the {@link
* #begin begin} and {@link #end end} callback methods. It is
* similar to {@link javax.media.opengl.GL#glVertex3f glVertex3f},
* and it defines the vertices of the triangles created by the
* tessellation process. The method takes a reference as its only
* argument. This reference is identical to the opaque reference
* provided by the user when the vertex was described (see {@link
* GLU#gluTessVertex gluTessVertex}).
*
* @param vertexData
* Specifics a reference to the vertices of the triangles created
* byt the tessellatin process.
*
* @see GLU#gluTessCallback gluTessCallback
* @see #vertexData vertexData
*/
void vertex(Object vertexData);
/**
* The same as the {@link #end end} callback method except that it
* takes an additional reference argument. This reference is
* identical to the opaque reference provided when {@link
* GLU#gluTessBeginPolygon gluTessBeginPolygon} was called.
*
* @param polygonData
* Specifics a reference to user-defined data.
*
* @see GLU#gluTessCallback gluTessCallback
* @see #beginData beginData
* @see #end end
*/
void endData(Object polygonData);
/**
* The <b>combine</b> callback method is called to create a new vertex when
* the tessellation detects an intersection, or wishes to merge features. The
* method takes four arguments: an array of three elements each of type
* double, an array of four references, an array of four elements each of
* type float, and a reference to a reference.<P>
*
* The vertex is defined as a linear combination of up to four existing
* vertices, stored in <i>data</i>. The coefficients of the linear combination
* are given by <i>weight</i>; these weights always add up to 1. All vertex
* pointers are valid even when some of the weights are 0. <i>coords</i> gives
* the location of the new vertex.<P>
*
* The user must allocate another vertex, interpolate parameters using
* <i>data</i> and <i>weight</i>, and return the new vertex pointer in
* <i>outData</i>. This handle is supplied during rendering callbacks. The
* user is responsible for freeing the memory some time after
* {@link GLU#gluTessEndPolygon gluTessEndPolygon} is
* called.<P>
*
* For example, if the polygon lies in an arbitrary plane in 3-space, and a
* color is associated with each vertex, the <b>GLU_TESS_COMBINE</b>
* callback might look like this:
* </UL>
* <PRE>
* void myCombine(double[] coords, Object[] data,
* float[] weight, Object[] outData)
* {
* MyVertex newVertex = new MyVertex();
*
* newVertex.x = coords[0];
* newVertex.y = coords[1];
* newVertex.z = coords[2];
* newVertex.r = weight[0]*data[0].r +
* weight[1]*data[1].r +
* weight[2]*data[2].r +
* weight[3]*data[3].r;
* newVertex.g = weight[0]*data[0].g +
* weight[1]*data[1].g +
* weight[2]*data[2].g +
* weight[3]*data[3].g;
* newVertex.b = weight[0]*data[0].b +
* weight[1]*data[1].b +
* weight[2]*data[2].b +
* weight[3]*data[3].b;
* newVertex.a = weight[0]*data[0].a +
* weight[1]*data[1].a +
* weight[2]*data[2].a +
* weight[3]*data[3].a;
* outData = newVertex;
* }</PRE>
*
* @param coords
* Specifics the location of the new vertex.
* @param data
* Specifics the vertices used to create the new vertex.
* @param weight
* Specifics the weights used to create the new vertex.
* @param outData
* Reference user the put the coodinates of the new vertex.
*
* @see GLU#gluTessCallback gluTessCallback
* @see #combineData combineData
*/
void combine(double[] coords, Object[] data, float[] weight, Object[] outData);
/**
* The same as the {@link #vertex vertex} callback method except
* that it takes an additional reference argument. This reference is
* identical to the opaque reference provided when {@link
* GLU#gluTessBeginPolygon gluTessBeginPolygon} was called.
*
* @param vertexData
* Specifics a reference to the vertices of the triangles created
* byt the tessellatin process.
* @param polygonData
* Specifics a reference to user-defined data.
*
* @see GLU#gluTessCallback gluTessCallback
* @see #vertex vertex
*/
void vertexData(Object vertexData, Object polygonData);
/**
* The same as the {@link #combine combine} callback method except
* that it takes an additional reference argument. This reference is
* identical to the opaque reference provided when {@link
* GLU#gluTessBeginPolygon gluTessBeginPolygon} was called.
*
* @param coords
* Specifics the location of the new vertex.
* @param data
* Specifics the vertices used to create the new vertex.
* @param weight
* Specifics the weights used to create the new vertex.
* @param outData
* Reference user the put the coodinates of the new vertex.
* @param polygonData
* Specifics a reference to user-defined data.
*
* @see GLU#gluTessCallback gluTessCallback
* @see #combine combine
*/
void combineData(double[] coords, Object[] data, float[] weight, Object[] outData, Object polygonData);
/**
* The <b>error</b> callback method is called when an error is encountered.
* The one argument is of type int; it indicates the specific error that
* occurred and will be set to one of <b>GLU_TESS_MISSING_BEGIN_POLYGON</b>,
* <b>GLU_TESS_MISSING_END_POLYGON</b>, <b>GLU_TESS_MISSING_BEGIN_CONTOUR</b>,
* <b>GLU_TESS_MISSING_END_CONTOUR</b>, <b>GLU_TESS_COORD_TOO_LARGE</b>,
* <b>GLU_TESS_NEED_COMBINE_CALLBACK</b> or <b>GLU_OUT_OF_MEMORY</b>.
* Character strings describing these errors can be retrieved with the
* {@link GLU#gluErrorString gluErrorString} call.<P>
*
* The GLU library will recover from the first four errors by inserting the
* missing call(s). <b>GLU_TESS_COORD_TOO_LARGE</b> indicates that some
* vertex coordinate exceeded the predefined constant
* <b>GLU_TESS_MAX_COORD</b> in absolute value, and that the value has been
* clamped. (Coordinate values must be small enough so that two can be
* multiplied together without overflow.)
* <b>GLU_TESS_NEED_COMBINE_CALLBACK</b> indicates that the tessellation
* detected an intersection between two edges in the input data, and the
* <b>GLU_TESS_COMBINE</b> or <b>GLU_TESS_COMBINE_DATA</b> callback was not
* provided. No output is generated. <b>GLU_OUT_OF_MEMORY</b> indicates that
* there is not enough memory so no output is generated.
*
* @param errnum
* Specifics the error number code.
*
* @see GLU#gluTessCallback gluTessCallback
* @see #errorData errorData
*/
void error(int errnum);
/**
* The end callback serves the same purpose as
* {@link javax.media.opengl.GL#glEnd glEnd}. It indicates the end of a
* primitive and it takes no arguments.
*
* @see GLU#gluTessCallback gluTessCallback
* @see #begin begin
* @see #endData endData
*/
void end();
/**
* The same as the {@link #error error} callback method except that
* it takes an additional reference argument. This reference is
* identical to the opaque reference provided when {@link
* GLU#gluTessBeginPolygon gluTessBeginPolygon} was called.
*
* @param errnum
* Specifics the error number code.
* @param polygonData
* Specifics a reference to user-defined data.
*
* @see GLU#gluTessCallback gluTessCallback
* @see #error error
*/
void errorData(int errnum, Object polygonData);
/**
* The same as the {@link #end end} callback method except that it
* takes an additional reference argument. This reference is
* identical to the opaque reference provided when {@link
* GLU#gluTessBeginPolygon gluTessBeginPolygon} was called.
*
* @param polygonData
* Specifics a reference to user-defined data.
*
* @see GLU#gluTessCallback gluTessCallback
* @see #beginData beginData
* @see #end end
*/
void endData(Object polygonData);
/**
* The <b>combine</b> callback method is called to create a new vertex when
* the tessellation detects an intersection, or wishes to merge features. The
* method takes four arguments: an array of three elements each of type
* double, an array of four references, an array of four elements each of
* type float, and a reference to a reference.<P>
*
* The vertex is defined as a linear combination of up to four existing
* vertices, stored in <i>data</i>. The coefficients of the linear combination
* are given by <i>weight</i>; these weights always add up to 1. All vertex
* pointers are valid even when some of the weights are 0. <i>coords</i> gives
* the location of the new vertex.<P>
*
* The user must allocate another vertex, interpolate parameters using
* <i>data</i> and <i>weight</i>, and return the new vertex pointer in
* <i>outData</i>. This handle is supplied during rendering callbacks. The
* user is responsible for freeing the memory some time after
* {@link GLU#gluTessEndPolygon gluTessEndPolygon} is
* called.<P>
*
* For example, if the polygon lies in an arbitrary plane in 3-space, and a
* color is associated with each vertex, the <b>GLU_TESS_COMBINE</b>
* callback might look like this:
* </UL>
* <PRE>
* void myCombine(double[] coords, Object[] data,
* float[] weight, Object[] outData)
* {
* MyVertex newVertex = new MyVertex();
*
* newVertex.x = coords[0];
* newVertex.y = coords[1];
* newVertex.z = coords[2];
* newVertex.r = weight[0]*data[0].r +
* weight[1]*data[1].r +
* weight[2]*data[2].r +
* weight[3]*data[3].r;
* newVertex.g = weight[0]*data[0].g +
* weight[1]*data[1].g +
* weight[2]*data[2].g +
* weight[3]*data[3].g;
* newVertex.b = weight[0]*data[0].b +
* weight[1]*data[1].b +
* weight[2]*data[2].b +
* weight[3]*data[3].b;
* newVertex.a = weight[0]*data[0].a +
* weight[1]*data[1].a +
* weight[2]*data[2].a +
* weight[3]*data[3].a;
* outData = newVertex;
* }</PRE>
*
* @param coords
* Specifics the location of the new vertex.
* @param data
* Specifics the vertices used to create the new vertex.
* @param weight
* Specifics the weights used to create the new vertex.
* @param outData
* Reference user the put the coodinates of the new vertex.
*
* @see GLU#gluTessCallback gluTessCallback
* @see #combineData combineData
*/
void combine(double[] coords, Object[] data,
float[] weight, Object[] outData);
/**
* The same as the {@link #combine combine} callback method except
* that it takes an additional reference argument. This reference is
* identical to the opaque reference provided when {@link
* GLU#gluTessBeginPolygon gluTessBeginPolygon} was called.
*
* @param coords
* Specifics the location of the new vertex.
* @param data
* Specifics the vertices used to create the new vertex.
* @param weight
* Specifics the weights used to create the new vertex.
* @param outData
* Reference user the put the coodinates of the new vertex.
* @param polygonData
* Specifics a reference to user-defined data.
*
* @see GLU#gluTessCallback gluTessCallback
* @see #combine combine
*/
void combineData(double[] coords, Object[] data,
float[] weight, Object[] outData,
Object polygonData);
/**
* The <b>error</b> callback method is called when an error is encountered.
* The one argument is of type int; it indicates the specific error that
* occurred and will be set to one of <b>GLU_TESS_MISSING_BEGIN_POLYGON</b>,
* <b>GLU_TESS_MISSING_END_POLYGON</b>, <b>GLU_TESS_MISSING_BEGIN_CONTOUR</b>,
* <b>GLU_TESS_MISSING_END_CONTOUR</b>, <b>GLU_TESS_COORD_TOO_LARGE</b>,
* <b>GLU_TESS_NEED_COMBINE_CALLBACK</b> or <b>GLU_OUT_OF_MEMORY</b>.
* Character strings describing these errors can be retrieved with the
* {@link GLU#gluErrorString gluErrorString} call.<P>
*
* The GLU library will recover from the first four errors by inserting the
* missing call(s). <b>GLU_TESS_COORD_TOO_LARGE</b> indicates that some
* vertex coordinate exceeded the predefined constant
* <b>GLU_TESS_MAX_COORD</b> in absolute value, and that the value has been
* clamped. (Coordinate values must be small enough so that two can be
* multiplied together without overflow.)
* <b>GLU_TESS_NEED_COMBINE_CALLBACK</b> indicates that the tessellation
* detected an intersection between two edges in the input data, and the
* <b>GLU_TESS_COMBINE</b> or <b>GLU_TESS_COMBINE_DATA</b> callback was not
* provided. No output is generated. <b>GLU_OUT_OF_MEMORY</b> indicates that
* there is not enough memory so no output is generated.
*
* @param errnum
* Specifics the error number code.
*
* @see GLU#gluTessCallback gluTessCallback
* @see #errorData errorData
*/
void error(int errnum);
/**
* The same as the {@link #error error} callback method except that
* it takes an additional reference argument. This reference is
* identical to the opaque reference provided when {@link
* GLU#gluTessBeginPolygon gluTessBeginPolygon} was called.
*
* @param errnum
* Specifics the error number code.
* @param polygonData
* Specifics a reference to user-defined data.
*
* @see GLU#gluTessCallback gluTessCallback
* @see #error error
*/
void errorData(int errnum, Object polygonData);
//void mesh(com.sun.opengl.impl.tessellator.GLUmesh mesh);
// void mesh(com.sun.opengl.impl.tessellator.GLUmesh mesh);
}
@@ -31,57 +31,57 @@
*/
/*
* Portions Copyright (C) 2003-2006 Sun Microsystems, Inc.
* All rights reserved.
*/
* Portions Copyright (C) 2003-2006 Sun Microsystems, Inc.
* All rights reserved.
*/
/*
** License Applicability. Except to the extent portions of this file are
** made subject to an alternative license as permitted in the SGI Free
** Software License B, Version 1.1 (the "License"), the contents of this
** file are subject only to the provisions of the License. You may not use
** this file except in compliance with the License. You may obtain a copy
** of the License at Silicon Graphics, Inc., attn: Legal Services, 1600
** Amphitheatre Parkway, Mountain View, CA 94043-1351, or at:
**
** http://oss.sgi.com/projects/FreeB
**
** Note that, as provided in the License, the Software is distributed on an
** "AS IS" basis, with ALL EXPRESS AND IMPLIED WARRANTIES AND CONDITIONS
** DISCLAIMED, INCLUDING, WITHOUT LIMITATION, ANY IMPLIED WARRANTIES AND
** CONDITIONS OF MERCHANTABILITY, SATISFACTORY QUALITY, FITNESS FOR A
** PARTICULAR PURPOSE, AND NON-INFRINGEMENT.
**
** NOTE: The Original Code (as defined below) has been licensed to Sun
** Microsystems, Inc. ("Sun") under the SGI Free Software License B
** (Version 1.1), shown above ("SGI License"). Pursuant to Section
** 3.2(3) of the SGI License, Sun is distributing the Covered Code to
** you under an alternative license ("Alternative License"). This
** Alternative License includes all of the provisions of the SGI License
** except that Section 2.2 and 11 are omitted. Any differences between
** the Alternative License and the SGI License are offered solely by Sun
** and not by SGI.
**
** Original Code. The Original Code is: OpenGL Sample Implementation,
** Version 1.2.1, released January 26, 2000, developed by Silicon Graphics,
** Inc. The Original Code is Copyright (c) 1991-2000 Silicon Graphics, Inc.
** Copyright in any portions created by third parties is as indicated
** elsewhere herein. All Rights Reserved.
**
** Additional Notice Provisions: The application programming interfaces
** established by SGI in conjunction with the Original Code are The
** OpenGL(R) Graphics System: A Specification (Version 1.2.1), released
** April 1, 1999; The OpenGL(R) Graphics System Utility Library (Version
** 1.3), released November 4, 1998; and OpenGL(R) Graphics with the X
** Window System(R) (Version 1.3), released October 19, 1998. This software
** was created using the OpenGL(R) version 1.2.1 Sample Implementation
** published by SGI, but has not been independently verified as being
** compliant with the OpenGL(R) version 1.2.1 Specification.
**
** Author: Eric Veach, July 1994
** Java Port: Pepijn Van Eeckhoudt, July 2003
** Java Port: Nathan Parker Burg, August 2003
*/
** License Applicability. Except to the extent portions of this file are
** made subject to an alternative license as permitted in the SGI Free
** Software License B, Version 1.1 (the "License"), the contents of this
** file are subject only to the provisions of the License. You may not use
** this file except in compliance with the License. You may obtain a copy
** of the License at Silicon Graphics, Inc., attn: Legal Services, 1600
** Amphitheatre Parkway, Mountain View, CA 94043-1351, or at:
**
** http://oss.sgi.com/projects/FreeB
**
** Note that, as provided in the License, the Software is distributed on an
** "AS IS" basis, with ALL EXPRESS AND IMPLIED WARRANTIES AND CONDITIONS
** DISCLAIMED, INCLUDING, WITHOUT LIMITATION, ANY IMPLIED WARRANTIES AND
** CONDITIONS OF MERCHANTABILITY, SATISFACTORY QUALITY, FITNESS FOR A
** PARTICULAR PURPOSE, AND NON-INFRINGEMENT.
**
** NOTE: The Original Code (as defined below) has been licensed to Sun
** Microsystems, Inc. ("Sun") under the SGI Free Software License B
** (Version 1.1), shown above ("SGI License"). Pursuant to Section
** 3.2(3) of the SGI License, Sun is distributing the Covered Code to
** you under an alternative license ("Alternative License"). This
** Alternative License includes all of the provisions of the SGI License
** except that Section 2.2 and 11 are omitted. Any differences between
** the Alternative License and the SGI License are offered solely by Sun
** and not by SGI.
**
** Original Code. The Original Code is: OpenGL Sample Implementation,
** Version 1.2.1, released January 26, 2000, developed by Silicon Graphics,
** Inc. The Original Code is Copyright (c) 1991-2000 Silicon Graphics, Inc.
** Copyright in any portions created by third parties is as indicated
** elsewhere herein. All Rights Reserved.
**
** Additional Notice Provisions: The application programming interfaces
** established by SGI in conjunction with the Original Code are The
** OpenGL(R) Graphics System: A Specification (Version 1.2.1), released
** April 1, 1999; The OpenGL(R) Graphics System Utility Library (Version
** 1.3), released November 4, 1998; and OpenGL(R) Graphics with the X
** Window System(R) (Version 1.3), released October 19, 1998. This software
** was created using the OpenGL(R) version 1.2.1 Sample Implementation
** published by SGI, but has not been independently verified as being
** compliant with the OpenGL(R) version 1.2.1 Specification.
**
** Author: Eric Veach, July 1994
** Java Port: Pepijn Van Eeckhoudt, July 2003
** Java Port: Nathan Parker Burg, August 2003
*/
package org.lwjglx.util.glu;
/**
@@ -94,23 +94,28 @@ package org.lwjglx.util.glu;
* @author Java Port: Pepijn Van Eechhoudt, July 2003
* @author Java Port: Nathan Parker Burg, August 2003
*/
public class GLUtessellatorCallbackAdapter implements GLUtessellatorCallback {
public void begin(int type) {}
public void edgeFlag(boolean boundaryEdge) {}
public void vertex(Object vertexData) {}
public void end() {}
// public void mesh(com.sun.opengl.impl.tessellator.GLUmesh mesh) {}
// public void mesh(com.sun.opengl.impl.tessellator.GLUmesh mesh) {}
public void error(int errnum) {}
public void combine(double[] coords, Object[] data,
float[] weight, Object[] outData) {}
public void combine(double[] coords, Object[] data, float[] weight, Object[] outData) {}
public void beginData(int type, Object polygonData) {}
public void edgeFlagData(boolean boundaryEdge,
Object polygonData) {}
public void edgeFlagData(boolean boundaryEdge, Object polygonData) {}
public void vertexData(Object vertexData, Object polygonData) {}
public void endData(Object polygonData) {}
public void errorData(int errnum, Object polygonData) {}
public void combineData(double[] coords, Object[] data,
float[] weight, Object[] outData,
Object polygonData) {}
public void combineData(double[] coords, Object[] data, float[] weight, Object[] outData, Object polygonData) {}
}
+250 -259
View File
@@ -31,13 +31,12 @@
*/
package org.lwjglx.util.glu;
import java.nio.ByteBuffer;
import org.lwjglx.BufferUtils;
import static org.lwjgl.opengl.GL11.*;
import static org.lwjglx.util.glu.GLU.*;
import java.nio.ByteBuffer;
import org.lwjglx.BufferUtils;
/**
* MipMap.java
*
@@ -47,307 +46,299 @@ import static org.lwjglx.util.glu.GLU.*;
*/
public class MipMap extends Util {
/**
* Method gluBuild2DMipmaps
*
* @param target
* @param components
* @param width
* @param height
* @param format
* @param type
* @param data
* @return int
*/
public static int gluBuild2DMipmaps(final int target,
final int components, final int width, final int height,
final int format, final int type, final ByteBuffer data) {
if ( width < 1 || height < 1 ) return GLU_INVALID_VALUE;
/**
* Method gluBuild2DMipmaps
*
* @param target
* @param components
* @param width
* @param height
* @param format
* @param type
* @param data
* @return int
*/
public static int gluBuild2DMipmaps(
final int target,
final int components,
final int width,
final int height,
final int format,
final int type,
final ByteBuffer data) {
if (width < 1 || height < 1) return GLU_INVALID_VALUE;
final int bpp = bytesPerPixel(format, type);
if ( bpp == 0 )
return GLU_INVALID_ENUM;
final int bpp = bytesPerPixel(format, type);
if (bpp == 0) return GLU_INVALID_ENUM;
final int maxSize = glGetIntegerv(GL_MAX_TEXTURE_SIZE);
final int maxSize = glGetIntegerv(GL_MAX_TEXTURE_SIZE);
int w = nearestPower(width);
if ( w > maxSize )
w = maxSize;
int w = nearestPower(width);
if (w > maxSize) w = maxSize;
int h = nearestPower(height);
if ( h > maxSize )
h = maxSize;
int h = nearestPower(height);
if (h > maxSize) h = maxSize;
// Get current glPixelStore state
PixelStoreState pss = new PixelStoreState();
// Get current glPixelStore state
PixelStoreState pss = new PixelStoreState();
// set pixel packing
glPixelStorei(GL_PACK_ROW_LENGTH, 0);
glPixelStorei(GL_PACK_ALIGNMENT, 1);
glPixelStorei(GL_PACK_SKIP_ROWS, 0);
glPixelStorei(GL_PACK_SKIP_PIXELS, 0);
// set pixel packing
glPixelStorei(GL_PACK_ROW_LENGTH, 0);
glPixelStorei(GL_PACK_ALIGNMENT, 1);
glPixelStorei(GL_PACK_SKIP_ROWS, 0);
glPixelStorei(GL_PACK_SKIP_PIXELS, 0);
ByteBuffer image;
int retVal = 0;
boolean done = false;
ByteBuffer image;
int retVal = 0;
boolean done = false;
if ( w != width || h != height ) {
// must rescale image to get "top" mipmap texture image
image = BufferUtils.createByteBuffer((w + 4) * h * bpp);
int error = gluScaleImage(format, width, height, type, data, w, h, type, image);
if ( error != 0 ) {
retVal = error;
done = true;
}
if (w != width || h != height) {
// must rescale image to get "top" mipmap texture image
image = BufferUtils.createByteBuffer((w + 4) * h * bpp);
int error = gluScaleImage(format, width, height, type, data, w, h, type, image);
if (error != 0) {
retVal = error;
done = true;
}
/* set pixel unpacking */
glPixelStorei(GL_UNPACK_ROW_LENGTH, 0);
glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
glPixelStorei(GL_UNPACK_SKIP_ROWS, 0);
glPixelStorei(GL_UNPACK_SKIP_PIXELS, 0);
} else {
image = data;
}
/* set pixel unpacking */
glPixelStorei(GL_UNPACK_ROW_LENGTH, 0);
glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
glPixelStorei(GL_UNPACK_SKIP_ROWS, 0);
glPixelStorei(GL_UNPACK_SKIP_PIXELS, 0);
} else {
image = data;
}
ByteBuffer bufferA = null;
ByteBuffer bufferB = null;
ByteBuffer bufferA = null;
ByteBuffer bufferB = null;
int level = 0;
while ( !done ) {
if (image != data) {
/* set pixel unpacking */
glPixelStorei(GL_UNPACK_ROW_LENGTH, 0);
glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
glPixelStorei(GL_UNPACK_SKIP_ROWS, 0);
glPixelStorei(GL_UNPACK_SKIP_PIXELS, 0);
}
int level = 0;
while (!done) {
if (image != data) {
/* set pixel unpacking */
glPixelStorei(GL_UNPACK_ROW_LENGTH, 0);
glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
glPixelStorei(GL_UNPACK_SKIP_ROWS, 0);
glPixelStorei(GL_UNPACK_SKIP_PIXELS, 0);
}
glTexImage2D(target, level, components, w, h, 0, format, type, image);
glTexImage2D(target, level, components, w, h, 0, format, type, image);
if ( w == 1 && h == 1 )
break;
if (w == 1 && h == 1) break;
final int newW = (w < 2) ? 1 : w >> 1;
final int newH = (h < 2) ? 1 : h >> 1;
final int newW = (w < 2) ? 1 : w >> 1;
final int newH = (h < 2) ? 1 : h >> 1;
final ByteBuffer newImage;
final ByteBuffer newImage;
if ( bufferA == null )
newImage = (bufferA = BufferUtils.createByteBuffer((newW + 4) * newH * bpp));
else if ( bufferB == null )
newImage = (bufferB = BufferUtils.createByteBuffer((newW + 4) * newH * bpp));
else
newImage = bufferB;
if (bufferA == null) newImage = (bufferA = BufferUtils.createByteBuffer((newW + 4) * newH * bpp));
else if (bufferB == null) newImage = (bufferB = BufferUtils.createByteBuffer((newW + 4) * newH * bpp));
else newImage = bufferB;
int error = gluScaleImage(format, w, h, type, image, newW, newH, type, newImage);
if ( error != 0 ) {
retVal = error;
done = true;
}
int error = gluScaleImage(format, w, h, type, image, newW, newH, type, newImage);
if (error != 0) {
retVal = error;
done = true;
}
image = newImage;
if ( bufferB != null )
bufferB = bufferA;
image = newImage;
if (bufferB != null) bufferB = bufferA;
w = newW;
h = newH;
level++;
}
w = newW;
h = newH;
level++;
}
// Restore original glPixelStore state
pss.save();
// Restore original glPixelStore state
pss.save();
return retVal;
}
return retVal;
}
/**
* Method gluScaleImage.
* @param format
* @param widthIn
* @param heightIn
* @param typein
* @param dataIn
* @param widthOut
* @param heightOut
* @param typeOut
* @param dataOut
* @return int
*/
public static int gluScaleImage(int format,
int widthIn, int heightIn, int typein, ByteBuffer dataIn,
int widthOut, int heightOut, int typeOut, ByteBuffer dataOut) {
/**
* Method gluScaleImage.
* @param format
* @param widthIn
* @param heightIn
* @param typein
* @param dataIn
* @param widthOut
* @param heightOut
* @param typeOut
* @param dataOut
* @return int
*/
public static int gluScaleImage(
int format,
int widthIn,
int heightIn,
int typein,
ByteBuffer dataIn,
int widthOut,
int heightOut,
int typeOut,
ByteBuffer dataOut) {
final int components = compPerPix(format);
if ( components == -1 )
return GLU_INVALID_ENUM;
final int components = compPerPix(format);
if (components == -1) return GLU_INVALID_ENUM;
int i, j, k;
float[] tempIn, tempOut;
float sx, sy;
int sizein, sizeout;
int rowstride, rowlen;
int i, j, k;
float[] tempIn, tempOut;
float sx, sy;
int sizein, sizeout;
int rowstride, rowlen;
// temp image data
tempIn = new float[widthIn * heightIn * components];
tempOut = new float[widthOut * heightOut * components];
// temp image data
tempIn = new float[widthIn * heightIn * components];
tempOut = new float[widthOut * heightOut * components];
// Determine bytes per input type
switch ( typein ) {
case GL_UNSIGNED_BYTE:
sizein = 1;
break;
case GL_FLOAT:
sizein = 4;
break;
default:
return GL_INVALID_ENUM;
}
// Determine bytes per input type
switch (typein) {
case GL_UNSIGNED_BYTE:
sizein = 1;
break;
case GL_FLOAT:
sizein = 4;
break;
default:
return GL_INVALID_ENUM;
}
// Determine bytes per output type
switch ( typeOut ) {
case GL_UNSIGNED_BYTE:
sizeout = 1;
break;
case GL_FLOAT:
sizeout = 4;
break;
default:
return GL_INVALID_ENUM;
}
// Determine bytes per output type
switch (typeOut) {
case GL_UNSIGNED_BYTE:
sizeout = 1;
break;
case GL_FLOAT:
sizeout = 4;
break;
default:
return GL_INVALID_ENUM;
}
// Get glPixelStore state
PixelStoreState pss = new PixelStoreState();
// Get glPixelStore state
PixelStoreState pss = new PixelStoreState();
//Unpack the pixel data and convert to floating point
if ( pss.unpackRowLength > 0 )
rowlen = pss.unpackRowLength;
else
rowlen = widthIn;
// Unpack the pixel data and convert to floating point
if (pss.unpackRowLength > 0) rowlen = pss.unpackRowLength;
else rowlen = widthIn;
if ( sizein >= pss.unpackAlignment )
rowstride = components * rowlen;
else
rowstride = pss.unpackAlignment / sizein * ceil(components * rowlen * sizein, pss.unpackAlignment);
if (sizein >= pss.unpackAlignment) rowstride = components * rowlen;
else rowstride = pss.unpackAlignment / sizein * ceil(components * rowlen * sizein, pss.unpackAlignment);
switch ( typein ) {
case GL_UNSIGNED_BYTE:
k = 0;
dataIn.rewind();
for ( i = 0; i < heightIn; i++ ) {
int ubptr = i * rowstride + pss.unpackSkipRows * rowstride + pss.unpackSkipPixels * components;
for ( j = 0; j < widthIn * components; j++ ) {
tempIn[k++] = dataIn.get(ubptr++) & 0xff;
}
}
break;
case GL_FLOAT:
k = 0;
dataIn.rewind();
for ( i = 0; i < heightIn; i++ )
{
int fptr = 4 * (i * rowstride + pss.unpackSkipRows * rowstride + pss.unpackSkipPixels * components);
for ( j = 0; j < widthIn * components; j++ )
{
tempIn[k++] = dataIn.getFloat(fptr);
fptr += 4;
}
}
break;
default:
return GLU_INVALID_ENUM;
}
switch (typein) {
case GL_UNSIGNED_BYTE:
k = 0;
dataIn.rewind();
for (i = 0; i < heightIn; i++) {
int ubptr = i * rowstride + pss.unpackSkipRows * rowstride + pss.unpackSkipPixels * components;
for (j = 0; j < widthIn * components; j++) {
tempIn[k++] = dataIn.get(ubptr++) & 0xff;
}
}
break;
case GL_FLOAT:
k = 0;
dataIn.rewind();
for (i = 0; i < heightIn; i++) {
int fptr = 4 * (i * rowstride + pss.unpackSkipRows * rowstride + pss.unpackSkipPixels * components);
for (j = 0; j < widthIn * components; j++) {
tempIn[k++] = dataIn.getFloat(fptr);
fptr += 4;
}
}
break;
default:
return GLU_INVALID_ENUM;
}
// Do scaling
sx = (float)widthIn / (float)widthOut;
sy = (float)heightIn / (float)heightOut;
// Do scaling
sx = (float) widthIn / (float) widthOut;
sy = (float) heightIn / (float) heightOut;
float[] c = new float[components];
int src, dst;
float[] c = new float[components];
int src, dst;
for ( int iy = 0; iy < heightOut; iy++ ) {
for ( int ix = 0; ix < widthOut; ix++ ) {
int x0 = (int)(ix * sx);
int x1 = (int)((ix + 1) * sx);
int y0 = (int)(iy * sy);
int y1 = (int)((iy + 1) * sy);
for (int iy = 0; iy < heightOut; iy++) {
for (int ix = 0; ix < widthOut; ix++) {
int x0 = (int) (ix * sx);
int x1 = (int) ((ix + 1) * sx);
int y0 = (int) (iy * sy);
int y1 = (int) ((iy + 1) * sy);
int readPix = 0;
int readPix = 0;
// reset weighted pixel
for ( int ic = 0; ic < components; ic++ ) {
c[ic] = 0;
}
// reset weighted pixel
for (int ic = 0; ic < components; ic++) {
c[ic] = 0;
}
// create weighted pixel
for ( int ix0 = x0; ix0 < x1; ix0++ ) {
for ( int iy0 = y0; iy0 < y1; iy0++ ) {
// create weighted pixel
for (int ix0 = x0; ix0 < x1; ix0++) {
for (int iy0 = y0; iy0 < y1; iy0++) {
src = (iy0 * widthIn + ix0) * components;
src = (iy0 * widthIn + ix0) * components;
for ( int ic = 0; ic < components; ic++ ) {
c[ic] += tempIn[src + ic];
}
for (int ic = 0; ic < components; ic++) {
c[ic] += tempIn[src + ic];
}
readPix++;
}
}
readPix++;
}
}
// store weighted pixel
dst = (iy * widthOut + ix) * components;
// store weighted pixel
dst = (iy * widthOut + ix) * components;
if ( readPix == 0 ) {
// Image is sized up, caused by non power of two texture as input
src = (y0 * widthIn + x0) * components;
for ( int ic = 0; ic < components; ic++ ) {
tempOut[dst++] = tempIn[src + ic];
}
} else {
// sized down
for ( k = 0; k < components; k++ ) {
tempOut[dst++] = c[k] / readPix;
}
}
}
}
if (readPix == 0) {
// Image is sized up, caused by non power of two texture as input
src = (y0 * widthIn + x0) * components;
for (int ic = 0; ic < components; ic++) {
tempOut[dst++] = tempIn[src + ic];
}
} else {
// sized down
for (k = 0; k < components; k++) {
tempOut[dst++] = c[k] / readPix;
}
}
}
}
// Convert temp output
if (pss.packRowLength > 0) rowlen = pss.packRowLength;
else rowlen = widthOut;
// Convert temp output
if ( pss.packRowLength > 0 )
rowlen = pss.packRowLength;
else
rowlen = widthOut;
if (sizeout >= pss.packAlignment) rowstride = components * rowlen;
else rowstride = pss.packAlignment / sizeout * ceil(components * rowlen * sizeout, pss.packAlignment);
if ( sizeout >= pss.packAlignment )
rowstride = components * rowlen;
else
rowstride = pss.packAlignment / sizeout * ceil(components * rowlen * sizeout, pss.packAlignment);
switch (typeOut) {
case GL_UNSIGNED_BYTE:
k = 0;
for (i = 0; i < heightOut; i++) {
int ubptr = i * rowstride + pss.packSkipRows * rowstride + pss.packSkipPixels * components;
switch ( typeOut ) {
case GL_UNSIGNED_BYTE:
k = 0;
for ( i = 0; i < heightOut; i++ ) {
int ubptr = i * rowstride + pss.packSkipRows * rowstride + pss.packSkipPixels * components;
for (j = 0; j < widthOut * components; j++) {
dataOut.put(ubptr++, (byte) tempOut[k++]);
}
}
break;
case GL_FLOAT:
k = 0;
for (i = 0; i < heightOut; i++) {
int fptr = 4 * (i * rowstride + pss.unpackSkipRows * rowstride + pss.unpackSkipPixels * components);
for ( j = 0; j < widthOut * components; j++ ) {
dataOut.put(ubptr++, (byte)tempOut[k++]);
}
}
break;
case GL_FLOAT:
k = 0;
for ( i = 0; i < heightOut; i++ ) {
int fptr = 4 * (i * rowstride + pss.unpackSkipRows * rowstride + pss.unpackSkipPixels * components);
for (j = 0; j < widthOut * components; j++) {
dataOut.putFloat(fptr, tempOut[k++]);
fptr += 4;
}
}
break;
default:
return GLU_INVALID_ENUM;
}
for ( j = 0; j < widthOut * components; j++ ) {
dataOut.putFloat(fptr, tempOut[k++]);
fptr += 4;
}
}
break;
default:
return GLU_INVALID_ENUM;
}
return 0;
}
return 0;
}
}
+246 -288
View File
@@ -44,315 +44,273 @@ import static org.lwjglx.util.glu.GLU.*;
*/
public class PartialDisk extends Quadric {
private static final int CACHE_SIZE = 240;
private static final int CACHE_SIZE = 240;
/**
* Constructor for PartialDisk.
*/
public PartialDisk() {
super();
}
/**
* Constructor for PartialDisk.
*/
public PartialDisk() {
super();
}
/**
* renders a partial disk on the z=0 plane. A partial disk is similar to a
* full disk, except that only the subset of the disk from startAngle
* through startAngle + sweepAngle is included (where 0 degrees is along
* the +y axis, 90 degrees along the +x axis, 180 along the -y axis, and
* 270 along the -x axis).
*
* The partial disk has a radius of outerRadius, and contains a concentric
* circular hole with a radius of innerRadius. If innerRadius is zero, then
* no hole is generated. The partial disk is subdivided around the z axis
* into slices (like pizza slices), and also about the z axis into rings
* (as specified by slices and loops, respectively).
*
* With respect to orientation, the +z side of the partial disk is
* considered to be outside (see gluQuadricOrientation). This means that if
* the orientation is set to GLU.GLU_OUTSIDE, then any normals generated point
* along the +z axis. Otherwise, they point along the -z axis.
*
* If texturing is turned on (with gluQuadricTexture), texture coordinates
* are generated linearly such that where r=outerRadius, the value at (r, 0, 0)
* is (1, 0.5), at (0, r, 0) it is (0.5, 1), at (-r, 0, 0) it is (0, 0.5),
* and at (0, -r, 0) it is (0.5, 0).
*/
public void draw(
float innerRadius,
float outerRadius,
int slices,
int loops,
float startAngle,
float sweepAngle) {
/**
* renders a partial disk on the z=0 plane. A partial disk is similar to a
* full disk, except that only the subset of the disk from startAngle
* through startAngle + sweepAngle is included (where 0 degrees is along
* the +y axis, 90 degrees along the +x axis, 180 along the -y axis, and
* 270 along the -x axis).
*
* The partial disk has a radius of outerRadius, and contains a concentric
* circular hole with a radius of innerRadius. If innerRadius is zero, then
* no hole is generated. The partial disk is subdivided around the z axis
* into slices (like pizza slices), and also about the z axis into rings
* (as specified by slices and loops, respectively).
*
* With respect to orientation, the +z side of the partial disk is
* considered to be outside (see gluQuadricOrientation). This means that if
* the orientation is set to GLU.GLU_OUTSIDE, then any normals generated point
* along the +z axis. Otherwise, they point along the -z axis.
*
* If texturing is turned on (with gluQuadricTexture), texture coordinates
* are generated linearly such that where r=outerRadius, the value at (r, 0, 0)
* is (1, 0.5), at (0, r, 0) it is (0.5, 1), at (-r, 0, 0) it is (0, 0.5),
* and at (0, -r, 0) it is (0.5, 0).
*/
public void draw(float innerRadius, float outerRadius, int slices, int loops, float startAngle, float sweepAngle) {
int i, j;
float[] sinCache = new float[CACHE_SIZE];
float[] cosCache = new float[CACHE_SIZE];
float angle;
float sintemp, costemp;
float deltaRadius;
float radiusLow, radiusHigh;
float texLow = 0, texHigh = 0;
float angleOffset;
int slices2;
int finish;
int i, j;
float[] sinCache = new float[CACHE_SIZE];
float[] cosCache = new float[CACHE_SIZE];
float angle;
float sintemp, costemp;
float deltaRadius;
float radiusLow, radiusHigh;
float texLow = 0, texHigh = 0;
float angleOffset;
int slices2;
int finish;
if (slices >= CACHE_SIZE)
slices = CACHE_SIZE - 1;
if (slices < 2
|| loops < 1
|| outerRadius <= 0.0f
|| innerRadius < 0.0f
|| innerRadius > outerRadius) {
//gluQuadricError(qobj, GLU.GLU_INVALID_VALUE);
System.err.println("PartialDisk: GLU_INVALID_VALUE");
return;
}
if (slices >= CACHE_SIZE) slices = CACHE_SIZE - 1;
if (slices < 2 || loops < 1 || outerRadius <= 0.0f || innerRadius < 0.0f || innerRadius > outerRadius) {
// gluQuadricError(qobj, GLU.GLU_INVALID_VALUE);
System.err.println("PartialDisk: GLU_INVALID_VALUE");
return;
}
if (sweepAngle < -360.0f)
sweepAngle = 360.0f;
if (sweepAngle > 360.0f)
sweepAngle = 360.0f;
if (sweepAngle < 0) {
startAngle += sweepAngle;
sweepAngle = -sweepAngle;
}
if (sweepAngle < -360.0f) sweepAngle = 360.0f;
if (sweepAngle > 360.0f) sweepAngle = 360.0f;
if (sweepAngle < 0) {
startAngle += sweepAngle;
sweepAngle = -sweepAngle;
}
if (sweepAngle == 360.0f) {
slices2 = slices;
} else {
slices2 = slices + 1;
}
if (sweepAngle == 360.0f) {
slices2 = slices;
} else {
slices2 = slices + 1;
}
/* Compute length (needed for normal calculations) */
deltaRadius = outerRadius - innerRadius;
/* Compute length (needed for normal calculations) */
deltaRadius = outerRadius - innerRadius;
/* Cache is the vertex locations cache */
/* Cache is the vertex locations cache */
angleOffset = startAngle / 180.0f * PI;
for (i = 0; i <= slices; i++) {
angle = angleOffset + ((PI * sweepAngle) / 180.0f) * i / slices;
sinCache[i] = sin(angle);
cosCache[i] = cos(angle);
}
angleOffset = startAngle / 180.0f * PI;
for (i = 0; i <= slices; i++) {
angle = angleOffset + ((PI * sweepAngle) / 180.0f) * i / slices;
sinCache[i] = sin(angle);
cosCache[i] = cos(angle);
}
if (sweepAngle == 360.0f) {
sinCache[slices] = sinCache[0];
cosCache[slices] = cosCache[0];
}
if (sweepAngle == 360.0f) {
sinCache[slices] = sinCache[0];
cosCache[slices] = cosCache[0];
}
switch (super.normals) {
case GLU_FLAT :
case GLU_SMOOTH :
if (super.orientation == GLU_OUTSIDE) {
glNormal3f(0.0f, 0.0f, 1.0f);
} else {
glNormal3f(0.0f, 0.0f, -1.0f);
}
break;
default :
case GLU_NONE :
break;
}
switch (super.normals) {
case GLU_FLAT:
case GLU_SMOOTH:
if (super.orientation == GLU_OUTSIDE) {
glNormal3f(0.0f, 0.0f, 1.0f);
} else {
glNormal3f(0.0f, 0.0f, -1.0f);
}
break;
default:
case GLU_NONE:
break;
}
switch (super.drawStyle) {
case GLU_FILL :
if (innerRadius == .0f) {
finish = loops - 1;
/* Triangle strip for inner polygons */
glBegin(GL_TRIANGLE_FAN);
if (super.textureFlag) {
glTexCoord2f(0.5f, 0.5f);
}
glVertex3f(0.0f, 0.0f, 0.0f);
radiusLow = outerRadius - deltaRadius * ((float) (loops - 1) / loops);
if (super.textureFlag) {
texLow = radiusLow / outerRadius / 2;
}
switch (super.drawStyle) {
case GLU_FILL:
if (innerRadius == .0f) {
finish = loops - 1;
/* Triangle strip for inner polygons */
glBegin(GL_TRIANGLE_FAN);
if (super.textureFlag) {
glTexCoord2f(0.5f, 0.5f);
}
glVertex3f(0.0f, 0.0f, 0.0f);
radiusLow = outerRadius - deltaRadius * ((float) (loops - 1) / loops);
if (super.textureFlag) {
texLow = radiusLow / outerRadius / 2;
}
if (super.orientation == GLU_OUTSIDE) {
for (i = slices; i >= 0; i--) {
if (super.textureFlag) {
glTexCoord2f(
texLow * sinCache[i] + 0.5f,
texLow * cosCache[i] + 0.5f);
}
glVertex3f(radiusLow * sinCache[i], radiusLow * cosCache[i], 0.0f);
}
} else {
for (i = 0; i <= slices; i++) {
if (super.textureFlag) {
glTexCoord2f(
texLow * sinCache[i] + 0.5f,
texLow * cosCache[i] + 0.5f);
}
glVertex3f(radiusLow * sinCache[i], radiusLow * cosCache[i], 0.0f);
}
}
glEnd();
} else {
finish = loops;
}
for (j = 0; j < finish; j++) {
radiusLow = outerRadius - deltaRadius * ((float) j / loops);
radiusHigh = outerRadius - deltaRadius * ((float) (j + 1) / loops);
if (super.textureFlag) {
texLow = radiusLow / outerRadius / 2;
texHigh = radiusHigh / outerRadius / 2;
}
if (super.orientation == GLU_OUTSIDE) {
for (i = slices; i >= 0; i--) {
if (super.textureFlag) {
glTexCoord2f(texLow * sinCache[i] + 0.5f, texLow * cosCache[i] + 0.5f);
}
glVertex3f(radiusLow * sinCache[i], radiusLow * cosCache[i], 0.0f);
}
} else {
for (i = 0; i <= slices; i++) {
if (super.textureFlag) {
glTexCoord2f(texLow * sinCache[i] + 0.5f, texLow * cosCache[i] + 0.5f);
}
glVertex3f(radiusLow * sinCache[i], radiusLow * cosCache[i], 0.0f);
}
}
glEnd();
} else {
finish = loops;
}
for (j = 0; j < finish; j++) {
radiusLow = outerRadius - deltaRadius * ((float) j / loops);
radiusHigh = outerRadius - deltaRadius * ((float) (j + 1) / loops);
if (super.textureFlag) {
texLow = radiusLow / outerRadius / 2;
texHigh = radiusHigh / outerRadius / 2;
}
glBegin(GL_QUAD_STRIP);
for (i = 0; i <= slices; i++) {
if (super.orientation == GLU_OUTSIDE) {
if (super.textureFlag) {
glTexCoord2f(
texLow * sinCache[i] + 0.5f,
texLow * cosCache[i] + 0.5f);
}
glVertex3f(radiusLow * sinCache[i], radiusLow * cosCache[i], 0.0f);
glBegin(GL_QUAD_STRIP);
for (i = 0; i <= slices; i++) {
if (super.orientation == GLU_OUTSIDE) {
if (super.textureFlag) {
glTexCoord2f(texLow * sinCache[i] + 0.5f, texLow * cosCache[i] + 0.5f);
}
glVertex3f(radiusLow * sinCache[i], radiusLow * cosCache[i], 0.0f);
if (super.textureFlag) {
glTexCoord2f(
texHigh * sinCache[i] + 0.5f,
texHigh * cosCache[i] + 0.5f);
}
glVertex3f(
radiusHigh * sinCache[i],
radiusHigh * cosCache[i],
0.0f);
} else {
if (super.textureFlag) {
glTexCoord2f(
texHigh * sinCache[i] + 0.5f,
texHigh * cosCache[i] + 0.5f);
}
glVertex3f(
radiusHigh * sinCache[i],
radiusHigh * cosCache[i],
0.0f);
if (super.textureFlag) {
glTexCoord2f(texHigh * sinCache[i] + 0.5f, texHigh * cosCache[i] + 0.5f);
}
glVertex3f(radiusHigh * sinCache[i], radiusHigh * cosCache[i], 0.0f);
} else {
if (super.textureFlag) {
glTexCoord2f(texHigh * sinCache[i] + 0.5f, texHigh * cosCache[i] + 0.5f);
}
glVertex3f(radiusHigh * sinCache[i], radiusHigh * cosCache[i], 0.0f);
if (super.textureFlag) {
glTexCoord2f(
texLow * sinCache[i] + 0.5f,
texLow * cosCache[i] + 0.5f);
}
glVertex3f(radiusLow * sinCache[i], radiusLow * cosCache[i], 0.0f);
}
}
glEnd();
}
break;
case GLU_POINT :
glBegin(GL_POINTS);
for (i = 0; i < slices2; i++) {
sintemp = sinCache[i];
costemp = cosCache[i];
for (j = 0; j <= loops; j++) {
radiusLow = outerRadius - deltaRadius * ((float) j / loops);
if (super.textureFlag) {
glTexCoord2f(texLow * sinCache[i] + 0.5f, texLow * cosCache[i] + 0.5f);
}
glVertex3f(radiusLow * sinCache[i], radiusLow * cosCache[i], 0.0f);
}
}
glEnd();
}
break;
case GLU_POINT:
glBegin(GL_POINTS);
for (i = 0; i < slices2; i++) {
sintemp = sinCache[i];
costemp = cosCache[i];
for (j = 0; j <= loops; j++) {
radiusLow = outerRadius - deltaRadius * ((float) j / loops);
if (super.textureFlag) {
texLow = radiusLow / outerRadius / 2;
if (super.textureFlag) {
texLow = radiusLow / outerRadius / 2;
glTexCoord2f(
texLow * sinCache[i] + 0.5f,
texLow * cosCache[i] + 0.5f);
}
glVertex3f(radiusLow * sintemp, radiusLow * costemp, 0.0f);
}
}
glEnd();
break;
case GLU_LINE :
if (innerRadius == outerRadius) {
glBegin(GL_LINE_STRIP);
glTexCoord2f(texLow * sinCache[i] + 0.5f, texLow * cosCache[i] + 0.5f);
}
glVertex3f(radiusLow * sintemp, radiusLow * costemp, 0.0f);
}
}
glEnd();
break;
case GLU_LINE:
if (innerRadius == outerRadius) {
glBegin(GL_LINE_STRIP);
for (i = 0; i <= slices; i++) {
if (super.textureFlag) {
glTexCoord2f(sinCache[i] / 2 + 0.5f, cosCache[i] / 2 + 0.5f);
}
glVertex3f(innerRadius * sinCache[i], innerRadius * cosCache[i], 0.0f);
}
glEnd();
break;
}
for (j = 0; j <= loops; j++) {
radiusLow = outerRadius - deltaRadius * ((float) j / loops);
if (super.textureFlag) {
texLow = radiusLow / outerRadius / 2;
}
for (i = 0; i <= slices; i++) {
if (super.textureFlag) {
glTexCoord2f(sinCache[i] / 2 + 0.5f, cosCache[i] / 2 + 0.5f);
}
glVertex3f(innerRadius * sinCache[i], innerRadius * cosCache[i], 0.0f);
}
glEnd();
break;
}
for (j = 0; j <= loops; j++) {
radiusLow = outerRadius - deltaRadius * ((float) j / loops);
if (super.textureFlag) {
texLow = radiusLow / outerRadius / 2;
}
glBegin(GL_LINE_STRIP);
for (i = 0; i <= slices; i++) {
if (super.textureFlag) {
glTexCoord2f(
texLow * sinCache[i] + 0.5f,
texLow * cosCache[i] + 0.5f);
}
glVertex3f(radiusLow * sinCache[i], radiusLow * cosCache[i], 0.0f);
}
glEnd();
}
for (i = 0; i < slices2; i++) {
sintemp = sinCache[i];
costemp = cosCache[i];
glBegin(GL_LINE_STRIP);
for (j = 0; j <= loops; j++) {
radiusLow = outerRadius - deltaRadius * ((float) j / loops);
if (super.textureFlag) {
texLow = radiusLow / outerRadius / 2;
}
glBegin(GL_LINE_STRIP);
for (i = 0; i <= slices; i++) {
if (super.textureFlag) {
glTexCoord2f(texLow * sinCache[i] + 0.5f, texLow * cosCache[i] + 0.5f);
}
glVertex3f(radiusLow * sinCache[i], radiusLow * cosCache[i], 0.0f);
}
glEnd();
}
for (i = 0; i < slices2; i++) {
sintemp = sinCache[i];
costemp = cosCache[i];
glBegin(GL_LINE_STRIP);
for (j = 0; j <= loops; j++) {
radiusLow = outerRadius - deltaRadius * ((float) j / loops);
if (super.textureFlag) {
texLow = radiusLow / outerRadius / 2;
}
if (super.textureFlag) {
glTexCoord2f(
texLow * sinCache[i] + 0.5f,
texLow * cosCache[i] + 0.5f);
}
glVertex3f(radiusLow * sintemp, radiusLow * costemp, 0.0f);
}
glEnd();
}
break;
case GLU_SILHOUETTE :
if (sweepAngle < 360.0f) {
for (i = 0; i <= slices; i += slices) {
sintemp = sinCache[i];
costemp = cosCache[i];
glBegin(GL_LINE_STRIP);
for (j = 0; j <= loops; j++) {
radiusLow = outerRadius - deltaRadius * ((float) j / loops);
if (super.textureFlag) {
glTexCoord2f(texLow * sinCache[i] + 0.5f, texLow * cosCache[i] + 0.5f);
}
glVertex3f(radiusLow * sintemp, radiusLow * costemp, 0.0f);
}
glEnd();
}
break;
case GLU_SILHOUETTE:
if (sweepAngle < 360.0f) {
for (i = 0; i <= slices; i += slices) {
sintemp = sinCache[i];
costemp = cosCache[i];
glBegin(GL_LINE_STRIP);
for (j = 0; j <= loops; j++) {
radiusLow = outerRadius - deltaRadius * ((float) j / loops);
if (super.textureFlag) {
texLow = radiusLow / outerRadius / 2;
glTexCoord2f(
texLow * sinCache[i] + 0.5f,
texLow * cosCache[i] + 0.5f);
}
glVertex3f(radiusLow * sintemp, radiusLow * costemp, 0.0f);
}
glEnd();
}
}
for (j = 0; j <= loops; j += loops) {
radiusLow = outerRadius - deltaRadius * ((float) j / loops);
if (super.textureFlag) {
texLow = radiusLow / outerRadius / 2;
}
if (super.textureFlag) {
texLow = radiusLow / outerRadius / 2;
glTexCoord2f(texLow * sinCache[i] + 0.5f, texLow * cosCache[i] + 0.5f);
}
glVertex3f(radiusLow * sintemp, radiusLow * costemp, 0.0f);
}
glEnd();
}
}
for (j = 0; j <= loops; j += loops) {
radiusLow = outerRadius - deltaRadius * ((float) j / loops);
if (super.textureFlag) {
texLow = radiusLow / outerRadius / 2;
}
glBegin(GL_LINE_STRIP);
for (i = 0; i <= slices; i++) {
if (super.textureFlag) {
glTexCoord2f(
texLow * sinCache[i] + 0.5f,
texLow * cosCache[i] + 0.5f);
}
glVertex3f(radiusLow * sinCache[i], radiusLow * cosCache[i], 0.0f);
}
glEnd();
if (innerRadius == outerRadius)
break;
}
break;
default :
break;
}
}
glBegin(GL_LINE_STRIP);
for (i = 0; i <= slices; i++) {
if (super.textureFlag) {
glTexCoord2f(texLow * sinCache[i] + 0.5f, texLow * cosCache[i] + 0.5f);
}
glVertex3f(radiusLow * sinCache[i], radiusLow * cosCache[i], 0.0f);
}
glEnd();
if (innerRadius == outerRadius) break;
}
break;
default:
break;
}
}
}
@@ -42,43 +42,42 @@ import static org.lwjgl.opengl.GL11.*;
*/
class PixelStoreState extends Util {
public int unpackRowLength;
public int unpackAlignment;
public int unpackSkipRows;
public int unpackSkipPixels;
public int packRowLength;
public int packAlignment;
public int packSkipRows;
public int packSkipPixels;
public int unpackRowLength;
public int unpackAlignment;
public int unpackSkipRows;
public int unpackSkipPixels;
public int packRowLength;
public int packAlignment;
public int packSkipRows;
public int packSkipPixels;
/**
* Constructor for PixelStoreState.
*/
PixelStoreState() {
super();
load();
}
/**
* Constructor for PixelStoreState.
*/
PixelStoreState() {
super();
load();
}
public void load() {
unpackRowLength = glGetIntegerv(GL_UNPACK_ROW_LENGTH);
unpackAlignment = glGetIntegerv(GL_UNPACK_ALIGNMENT);
unpackSkipRows = glGetIntegerv(GL_UNPACK_SKIP_ROWS);
unpackSkipPixels = glGetIntegerv(GL_UNPACK_SKIP_PIXELS);
packRowLength = glGetIntegerv(GL_PACK_ROW_LENGTH);
packAlignment = glGetIntegerv(GL_PACK_ALIGNMENT);
packSkipRows = glGetIntegerv(GL_PACK_SKIP_ROWS);
packSkipPixels = glGetIntegerv(GL_PACK_SKIP_PIXELS);
}
public void save() {
glPixelStorei(GL_UNPACK_ROW_LENGTH, unpackRowLength);
glPixelStorei(GL_UNPACK_ALIGNMENT, unpackAlignment);
glPixelStorei(GL_UNPACK_SKIP_ROWS, unpackSkipRows);
glPixelStorei(GL_UNPACK_SKIP_PIXELS, unpackSkipPixels);
glPixelStorei(GL_PACK_ROW_LENGTH, packRowLength);
glPixelStorei(GL_PACK_ALIGNMENT, packAlignment);
glPixelStorei(GL_PACK_SKIP_ROWS, packSkipRows);
glPixelStorei(GL_PACK_SKIP_PIXELS, packSkipPixels);
}
public void load() {
unpackRowLength = glGetIntegerv(GL_UNPACK_ROW_LENGTH);
unpackAlignment = glGetIntegerv(GL_UNPACK_ALIGNMENT);
unpackSkipRows = glGetIntegerv(GL_UNPACK_SKIP_ROWS);
unpackSkipPixels = glGetIntegerv(GL_UNPACK_SKIP_PIXELS);
packRowLength = glGetIntegerv(GL_PACK_ROW_LENGTH);
packAlignment = glGetIntegerv(GL_PACK_ALIGNMENT);
packSkipRows = glGetIntegerv(GL_PACK_SKIP_ROWS);
packSkipPixels = glGetIntegerv(GL_PACK_SKIP_PIXELS);
}
public void save() {
glPixelStorei(GL_UNPACK_ROW_LENGTH, unpackRowLength);
glPixelStorei(GL_UNPACK_ALIGNMENT, unpackAlignment);
glPixelStorei(GL_UNPACK_SKIP_ROWS, unpackSkipRows);
glPixelStorei(GL_UNPACK_SKIP_PIXELS, unpackSkipPixels);
glPixelStorei(GL_PACK_ROW_LENGTH, packRowLength);
glPixelStorei(GL_PACK_ALIGNMENT, packAlignment);
glPixelStorei(GL_PACK_SKIP_ROWS, packSkipRows);
glPixelStorei(GL_PACK_SKIP_PIXELS, packSkipPixels);
}
}
+304 -312
View File
@@ -1,4 +1,4 @@
/*
/*
* Copyright (c) 2002-2008 LWJGL Project
* All rights reserved.
*
@@ -31,13 +31,12 @@
*/
package org.lwjglx.util.glu;
import static org.lwjgl.opengl.GL11.*;
import java.nio.FloatBuffer;
import java.nio.IntBuffer;
import org.lwjgl.BufferUtils;
import static org.lwjgl.opengl.GL11.*;
/**
* Project.java
* <p/>
@@ -48,364 +47,357 @@ import static org.lwjgl.opengl.GL11.*;
*/
public class Project extends Util {
private static final float[] IDENTITY_MATRIX =
new float[] {
1.0f, 0.0f, 0.0f, 0.0f,
0.0f, 1.0f, 0.0f, 0.0f,
0.0f, 0.0f, 1.0f, 0.0f,
0.0f, 0.0f, 0.0f, 1.0f };
private static final float[] IDENTITY_MATRIX = new float[] {
1.0f, 0.0f, 0.0f, 0.0f,
0.0f, 1.0f, 0.0f, 0.0f,
0.0f, 0.0f, 1.0f, 0.0f,
0.0f, 0.0f, 0.0f, 1.0f
};
private static final FloatBuffer matrix = BufferUtils.createFloatBuffer(16);
private static final FloatBuffer finalMatrix = BufferUtils.createFloatBuffer(16);
private static final FloatBuffer matrix = BufferUtils.createFloatBuffer(16);
private static final FloatBuffer finalMatrix = BufferUtils.createFloatBuffer(16);
private static final FloatBuffer tempMatrix = BufferUtils.createFloatBuffer(16);
private static final float[] in = new float[4];
private static final float[] out = new float[4];
private static final FloatBuffer tempMatrix = BufferUtils.createFloatBuffer(16);
private static final float[] in = new float[4];
private static final float[] out = new float[4];
private static final float[] forward = new float[3];
private static final float[] side = new float[3];
private static final float[] up = new float[3];
private static final float[] forward = new float[3];
private static final float[] side = new float[3];
private static final float[] up = new float[3];
/**
* Make matrix an identity matrix
*/
private static void __gluMakeIdentityf(FloatBuffer m) {
int oldPos = m.position();
m.put(IDENTITY_MATRIX);
m.position(oldPos);
}
/**
* Make matrix an identity matrix
*/
private static void __gluMakeIdentityf(FloatBuffer m) {
int oldPos = m.position();
m.put(IDENTITY_MATRIX);
m.position(oldPos);
}
/**
* Method __gluMultMatrixVecf
*
* @param finalMatrix
* @param in
* @param out
*/
private static void __gluMultMatrixVecf(FloatBuffer m, float[] in, float[] out) {
for (int i = 0; i < 4; i++) {
out[i] =
in[0] * m.get(m.position() + 0*4 + i)
+ in[1] * m.get(m.position() + 1*4 + i)
+ in[2] * m.get(m.position() + 2*4 + i)
+ in[3] * m.get(m.position() + 3*4 + i);
/**
* Method __gluMultMatrixVecf
*
* @param finalMatrix
* @param in
* @param out
*/
private static void __gluMultMatrixVecf(FloatBuffer m, float[] in, float[] out) {
for (int i = 0; i < 4; i++) {
out[i] = in[0] * m.get(m.position() + 0 * 4 + i)
+ in[1] * m.get(m.position() + 1 * 4 + i)
+ in[2] * m.get(m.position() + 2 * 4 + i)
+ in[3] * m.get(m.position() + 3 * 4 + i);
}
}
}
}
/**
* @param src
* @param inverse
*
* @return
*/
private static boolean __gluInvertMatrixf(FloatBuffer src, FloatBuffer inverse) {
int i, j, k, swap;
float t;
FloatBuffer temp = Project.tempMatrix;
/**
* @param src
* @param inverse
*
* @return
*/
private static boolean __gluInvertMatrixf(FloatBuffer src, FloatBuffer inverse) {
int i, j, k, swap;
float t;
FloatBuffer temp = Project.tempMatrix;
for (i = 0; i < 16; i++) {
temp.put(i, src.get(i + src.position()));
}
__gluMakeIdentityf(inverse);
for (i = 0; i < 4; i++) {
/*
* * Look for largest element in column
*/
swap = i;
for (j = i + 1; j < 4; j++) {
/*
* if (fabs(temp[j][i]) > fabs(temp[i][i])) { swap = j;
*/
if (Math.abs(temp.get(j * 4 + i)) > Math.abs(temp.get(i * 4 + i))) {
swap = j;
}
}
for (i = 0; i < 16; i++) {
temp.put(i, src.get(i + src.position()));
}
__gluMakeIdentityf(inverse);
if (swap != i) {
/*
* * Swap rows.
*/
for (k = 0; k < 4; k++) {
t = temp.get(i * 4 + k);
temp.put(i * 4 + k, temp.get(swap * 4 + k));
temp.put(swap * 4 + k, t);
for (i = 0; i < 4; i++) {
/*
* * Look for largest element in column
*/
swap = i;
for (j = i + 1; j < 4; j++) {
/*
* if (fabs(temp[j][i]) > fabs(temp[i][i])) { swap = j;
*/
if (Math.abs(temp.get(j*4 + i)) > Math.abs(temp.get(i* 4 + i))) {
swap = j;
}
}
t = inverse.get(i * 4 + k);
inverse.put(i * 4 + k, inverse.get(swap * 4 + k));
// inverse.put((i << 2) + k, inverse.get((swap << 2) + k));
inverse.put(swap * 4 + k, t);
// inverse.put((swap << 2) + k, t);
}
}
if (swap != i) {
/*
* * Swap rows.
*/
for (k = 0; k < 4; k++) {
t = temp.get(i*4 + k);
temp.put(i*4 + k, temp.get(swap*4 + k));
temp.put(swap*4 + k, t);
if (temp.get(i * 4 + i) == 0) {
/*
* * No non-zero pivot. The matrix is singular, which shouldn't *
* happen. This means the user gave us a bad matrix.
*/
return false;
}
t = inverse.get(i*4 + k);
inverse.put(i*4 + k, inverse.get(swap*4 + k));
//inverse.put((i << 2) + k, inverse.get((swap << 2) + k));
inverse.put(swap*4 + k, t);
//inverse.put((swap << 2) + k, t);
}
}
t = temp.get(i * 4 + i);
for (k = 0; k < 4; k++) {
temp.put(i * 4 + k, temp.get(i * 4 + k) / t);
inverse.put(i * 4 + k, inverse.get(i * 4 + k) / t);
}
for (j = 0; j < 4; j++) {
if (j != i) {
t = temp.get(j * 4 + i);
for (k = 0; k < 4; k++) {
temp.put(j * 4 + k, temp.get(j * 4 + k) - temp.get(i * 4 + k) * t);
inverse.put(j * 4 + k, inverse.get(j * 4 + k) - inverse.get(i * 4 + k) * t);
/*inverse.put(
(j << 2) + k,
inverse.get((j << 2) + k) - inverse.get((i << 2) + k) * t);*/
}
}
}
}
return true;
}
if (temp.get(i*4 + i) == 0) {
/*
* * No non-zero pivot. The matrix is singular, which shouldn't *
* happen. This means the user gave us a bad matrix.
*/
return false;
}
/**
* @param a
* @param b
* @param r
*/
private static void __gluMultMatricesf(FloatBuffer a, FloatBuffer b, FloatBuffer r) {
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 4; j++) {
r.put(
r.position() + i * 4 + j,
a.get(a.position() + i * 4 + 0) * b.get(b.position() + 0 * 4 + j)
+ a.get(a.position() + i * 4 + 1) * b.get(b.position() + 1 * 4 + j)
+ a.get(a.position() + i * 4 + 2) * b.get(b.position() + 2 * 4 + j)
+ a.get(a.position() + i * 4 + 3) * b.get(b.position() + 3 * 4 + j));
}
}
}
t = temp.get(i*4 + i);
for (k = 0; k < 4; k++) {
temp.put(i*4 + k, temp.get(i*4 + k)/t);
inverse.put(i*4 + k, inverse.get(i*4 + k)/t);
}
for (j = 0; j < 4; j++) {
if (j != i) {
t = temp.get(j*4 + i);
for (k = 0; k < 4; k++) {
temp.put(j*4 + k, temp.get(j*4 + k) - temp.get(i*4 + k) * t);
inverse.put(j*4 + k, inverse.get(j*4 + k) - inverse.get(i*4 + k) * t);
/*inverse.put(
(j << 2) + k,
inverse.get((j << 2) + k) - inverse.get((i << 2) + k) * t);*/
}
}
}
}
return true;
}
/**
* Method gluPerspective.
*
* @param fovy
* @param aspect
* @param zNear
* @param zFar
*/
public static void gluPerspective(float fovy, float aspect, float zNear, float zFar) {
float sine, cotangent, deltaZ;
float radians = fovy / 2 * GLU.PI / 180;
/**
* @param a
* @param b
* @param r
*/
private static void __gluMultMatricesf(FloatBuffer a, FloatBuffer b, FloatBuffer r) {
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 4; j++) {
r.put(r.position() + i*4 + j,
a.get(a.position() + i*4 + 0) * b.get(b.position() + 0*4 + j) + a.get(a.position() + i*4 + 1) * b.get(b.position() + 1*4 + j) + a.get(a.position() + i*4 + 2) * b.get(b.position() + 2*4 + j) + a.get(a.position() + i*4 + 3) * b.get(b.position() + 3*4 + j));
}
}
}
deltaZ = zFar - zNear;
sine = (float) Math.sin(radians);
/**
* Method gluPerspective.
*
* @param fovy
* @param aspect
* @param zNear
* @param zFar
*/
public static void gluPerspective(float fovy, float aspect, float zNear, float zFar) {
float sine, cotangent, deltaZ;
float radians = fovy / 2 * GLU.PI / 180;
if ((deltaZ == 0) || (sine == 0) || (aspect == 0)) {
return;
}
deltaZ = zFar - zNear;
sine = (float) Math.sin(radians);
cotangent = (float) Math.cos(radians) / sine;
if ((deltaZ == 0) || (sine == 0) || (aspect == 0)) {
return;
}
__gluMakeIdentityf(matrix);
cotangent = (float) Math.cos(radians) / sine;
matrix.put(0 * 4 + 0, cotangent / aspect);
matrix.put(1 * 4 + 1, cotangent);
matrix.put(2 * 4 + 2, -(zFar + zNear) / deltaZ);
matrix.put(2 * 4 + 3, -1);
matrix.put(3 * 4 + 2, -2 * zNear * zFar / deltaZ);
matrix.put(3 * 4 + 3, 0);
__gluMakeIdentityf(matrix);
glMultMatrix(matrix);
}
matrix.put(0 * 4 + 0, cotangent / aspect);
matrix.put(1 * 4 + 1, cotangent);
matrix.put(2 * 4 + 2, - (zFar + zNear) / deltaZ);
matrix.put(2 * 4 + 3, -1);
matrix.put(3 * 4 + 2, -2 * zNear * zFar / deltaZ);
matrix.put(3 * 4 + 3, 0);
/**
* Method gluLookAt
*
* @param eyex
* @param eyey
* @param eyez
* @param centerx
* @param centery
* @param centerz
* @param upx
* @param upy
* @param upz
*/
public static void gluLookAt(
float eyex,
float eyey,
float eyez,
float centerx,
float centery,
float centerz,
float upx,
float upy,
float upz) {
float[] forward = Project.forward;
float[] side = Project.side;
float[] up = Project.up;
glMultMatrix(matrix);
}
forward[0] = centerx - eyex;
forward[1] = centery - eyey;
forward[2] = centerz - eyez;
/**
* Method gluLookAt
*
* @param eyex
* @param eyey
* @param eyez
* @param centerx
* @param centery
* @param centerz
* @param upx
* @param upy
* @param upz
*/
public static void gluLookAt(
float eyex,
float eyey,
float eyez,
float centerx,
float centery,
float centerz,
float upx,
float upy,
float upz) {
float[] forward = Project.forward;
float[] side = Project.side;
float[] up = Project.up;
up[0] = upx;
up[1] = upy;
up[2] = upz;
forward[0] = centerx - eyex;
forward[1] = centery - eyey;
forward[2] = centerz - eyez;
normalize(forward);
up[0] = upx;
up[1] = upy;
up[2] = upz;
/* Side = forward x up */
cross(forward, up, side);
normalize(side);
normalize(forward);
/* Recompute up as: up = side x forward */
cross(side, forward, up);
/* Side = forward x up */
cross(forward, up, side);
normalize(side);
__gluMakeIdentityf(matrix);
matrix.put(0 * 4 + 0, side[0]);
matrix.put(1 * 4 + 0, side[1]);
matrix.put(2 * 4 + 0, side[2]);
/* Recompute up as: up = side x forward */
cross(side, forward, up);
matrix.put(0 * 4 + 1, up[0]);
matrix.put(1 * 4 + 1, up[1]);
matrix.put(2 * 4 + 1, up[2]);
__gluMakeIdentityf(matrix);
matrix.put(0 * 4 + 0, side[0]);
matrix.put(1 * 4 + 0, side[1]);
matrix.put(2 * 4 + 0, side[2]);
matrix.put(0 * 4 + 2, -forward[0]);
matrix.put(1 * 4 + 2, -forward[1]);
matrix.put(2 * 4 + 2, -forward[2]);
matrix.put(0 * 4 + 1, up[0]);
matrix.put(1 * 4 + 1, up[1]);
matrix.put(2 * 4 + 1, up[2]);
glMultMatrix(matrix);
glTranslatef(-eyex, -eyey, -eyez);
}
matrix.put(0 * 4 + 2, -forward[0]);
matrix.put(1 * 4 + 2, -forward[1]);
matrix.put(2 * 4 + 2, -forward[2]);
/**
* Method gluProject
*
* @param objx
* @param objy
* @param objz
* @param modelMatrix
* @param projMatrix
* @param viewport
* @param win_pos
*/
public static boolean gluProject(
float objx,
float objy,
float objz,
FloatBuffer modelMatrix,
FloatBuffer projMatrix,
IntBuffer viewport,
FloatBuffer win_pos) {
glMultMatrix(matrix);
glTranslatef(-eyex, -eyey, -eyez);
}
float[] in = Project.in;
float[] out = Project.out;
/**
* Method gluProject
*
* @param objx
* @param objy
* @param objz
* @param modelMatrix
* @param projMatrix
* @param viewport
* @param win_pos
*/
public static boolean gluProject(
float objx,
float objy,
float objz,
FloatBuffer modelMatrix,
FloatBuffer projMatrix,
IntBuffer viewport,
FloatBuffer win_pos) {
in[0] = objx;
in[1] = objy;
in[2] = objz;
in[3] = 1.0f;
float[] in = Project.in;
float[] out = Project.out;
__gluMultMatrixVecf(modelMatrix, in, out);
__gluMultMatrixVecf(projMatrix, out, in);
in[0] = objx;
in[1] = objy;
in[2] = objz;
in[3] = 1.0f;
if (in[3] == 0.0) return false;
__gluMultMatrixVecf(modelMatrix, in, out);
__gluMultMatrixVecf(projMatrix, out, in);
in[3] = (1.0f / in[3]) * 0.5f;
if (in[3] == 0.0)
return false;
// Map x, y and z to range 0-1
in[0] = in[0] * in[3] + 0.5f;
in[1] = in[1] * in[3] + 0.5f;
in[2] = in[2] * in[3] + 0.5f;
in[3] = (1.0f / in[3]) * 0.5f;
// Map x,y to viewport
win_pos.put(0, in[0] * viewport.get(viewport.position() + 2) + viewport.get(viewport.position() + 0));
win_pos.put(1, in[1] * viewport.get(viewport.position() + 3) + viewport.get(viewport.position() + 1));
win_pos.put(2, in[2]);
// Map x, y and z to range 0-1
in[0] = in[0] * in[3] + 0.5f;
in[1] = in[1] * in[3] + 0.5f;
in[2] = in[2] * in[3] + 0.5f;
return true;
}
// Map x,y to viewport
win_pos.put(0, in[0] * viewport.get(viewport.position() + 2) + viewport.get(viewport.position() + 0));
win_pos.put(1, in[1] * viewport.get(viewport.position() + 3) + viewport.get(viewport.position() + 1));
win_pos.put(2, in[2]);
/**
* Method gluUnproject
*
* @param winx
* @param winy
* @param winz
* @param modelMatrix
* @param projMatrix
* @param viewport
* @param obj_pos
*/
public static boolean gluUnProject(
float winx,
float winy,
float winz,
FloatBuffer modelMatrix,
FloatBuffer projMatrix,
IntBuffer viewport,
FloatBuffer obj_pos) {
float[] in = Project.in;
float[] out = Project.out;
return true;
}
__gluMultMatricesf(modelMatrix, projMatrix, finalMatrix);
/**
* Method gluUnproject
*
* @param winx
* @param winy
* @param winz
* @param modelMatrix
* @param projMatrix
* @param viewport
* @param obj_pos
*/
public static boolean gluUnProject(
float winx,
float winy,
float winz,
FloatBuffer modelMatrix,
FloatBuffer projMatrix,
IntBuffer viewport,
FloatBuffer obj_pos) {
float[] in = Project.in;
float[] out = Project.out;
if (!__gluInvertMatrixf(finalMatrix, finalMatrix)) return false;
__gluMultMatricesf(modelMatrix, projMatrix, finalMatrix);
in[0] = winx;
in[1] = winy;
in[2] = winz;
in[3] = 1.0f;
if (!__gluInvertMatrixf(finalMatrix, finalMatrix))
return false;
// Map x and y from window coordinates
in[0] = (in[0] - viewport.get(viewport.position() + 0)) / viewport.get(viewport.position() + 2);
in[1] = (in[1] - viewport.get(viewport.position() + 1)) / viewport.get(viewport.position() + 3);
in[0] = winx;
in[1] = winy;
in[2] = winz;
in[3] = 1.0f;
// Map to range -1 to 1
in[0] = in[0] * 2 - 1;
in[1] = in[1] * 2 - 1;
in[2] = in[2] * 2 - 1;
// Map x and y from window coordinates
in[0] = (in[0] - viewport.get(viewport.position() + 0)) / viewport.get(viewport.position() + 2);
in[1] = (in[1] - viewport.get(viewport.position() + 1)) / viewport.get(viewport.position() + 3);
__gluMultMatrixVecf(finalMatrix, in, out);
// Map to range -1 to 1
in[0] = in[0] * 2 - 1;
in[1] = in[1] * 2 - 1;
in[2] = in[2] * 2 - 1;
if (out[3] == 0.0) return false;
__gluMultMatrixVecf(finalMatrix, in, out);
out[3] = 1.0f / out[3];
if (out[3] == 0.0)
return false;
obj_pos.put(obj_pos.position() + 0, out[0] * out[3]);
obj_pos.put(obj_pos.position() + 1, out[1] * out[3]);
obj_pos.put(obj_pos.position() + 2, out[2] * out[3]);
out[3] = 1.0f / out[3];
return true;
}
obj_pos.put(obj_pos.position() + 0, out[0] * out[3]);
obj_pos.put(obj_pos.position() + 1, out[1] * out[3]);
obj_pos.put(obj_pos.position() + 2, out[2] * out[3]);
/**
* Method gluPickMatrix
*
* @param x
* @param y
* @param deltaX
* @param deltaY
* @param viewport
*/
public static void gluPickMatrix(float x, float y, float deltaX, float deltaY, IntBuffer viewport) {
if (deltaX <= 0 || deltaY <= 0) {
return;
}
return true;
}
/**
* Method gluPickMatrix
*
* @param x
* @param y
* @param deltaX
* @param deltaY
* @param viewport
*/
public static void gluPickMatrix(
float x,
float y,
float deltaX,
float deltaY,
IntBuffer viewport) {
if (deltaX <= 0 || deltaY <= 0) {
return;
}
/* Translate and scale the picked region to the entire window */
glTranslatef(
(viewport.get(viewport.position() + 2) - 2 * (x - viewport.get(viewport.position() + 0))) / deltaX,
(viewport.get(viewport.position() + 3) - 2 * (y - viewport.get(viewport.position() + 1))) / deltaY,
0);
glScalef(viewport.get(viewport.position() + 2) / deltaX, viewport.get(viewport.position() + 3) / deltaY, 1.0f);
}
/* Translate and scale the picked region to the entire window */
glTranslatef(
(viewport.get(viewport.position() + 2) - 2 * (x - viewport.get(viewport.position() + 0))) / deltaX,
(viewport.get(viewport.position() + 3) - 2 * (y - viewport.get(viewport.position() + 1))) / deltaY,
0);
glScalef(viewport.get(viewport.position() + 2) / deltaX, viewport.get(viewport.position() + 3) / deltaY, 1.0f);
}
}
+89 -92
View File
@@ -43,43 +43,43 @@ import static org.lwjglx.util.glu.GLU.*;
*/
public class Quadric {
protected int drawStyle;
protected int orientation;
protected boolean textureFlag;
protected int normals;
protected int drawStyle;
protected int orientation;
protected boolean textureFlag;
protected int normals;
/**
* Constructor for Quadric.
*/
public Quadric() {
super();
/**
* Constructor for Quadric.
*/
public Quadric() {
super();
drawStyle = GLU_FILL;
orientation = GLU_OUTSIDE;
textureFlag = false;
normals = GLU_SMOOTH;
}
drawStyle = GLU_FILL;
orientation = GLU_OUTSIDE;
textureFlag = false;
normals = GLU_SMOOTH;
}
/**
* Call glNormal3f after scaling normal to unit length.
*
* @param x
* @param y
* @param z
*/
protected void normal3f(float x, float y, float z) {
float mag;
/**
* Call glNormal3f after scaling normal to unit length.
*
* @param x
* @param y
* @param z
*/
protected void normal3f(float x, float y, float z) {
float mag;
mag = (float)Math.sqrt(x * x + y * y + z * z);
if (mag > 0.00001F) {
x /= mag;
y /= mag;
z /= mag;
}
glNormal3f(x, y, z);
}
mag = (float) Math.sqrt(x * x + y * y + z * z);
if (mag > 0.00001F) {
x /= mag;
y /= mag;
z /= mag;
}
glNormal3f(x, y, z);
}
/**
/**
* specifies the draw style for quadrics.
*
* The legal values are as follows:
@@ -95,11 +95,11 @@ public class Quadric {
*
* GLU.POINT: Quadrics are rendered as a set of points.
*
* @param drawStyle The drawStyle to set
*/
public void setDrawStyle(int drawStyle) {
this.drawStyle = drawStyle;
}
* @param drawStyle The drawStyle to set
*/
public void setDrawStyle(int drawStyle) {
this.drawStyle = drawStyle;
}
/**
* specifies what kind of normals are desired for quadrics.
@@ -112,11 +112,11 @@ public class Quadric {
* GLU.SMOOTH: One normal is generated for every vertex of a quadric. This
* is the default.
*
* @param normals The normals to set
*/
public void setNormals(int normals) {
this.normals = normals;
}
* @param normals The normals to set
*/
public void setNormals(int normals) {
this.normals = normals;
}
/**
* specifies what kind of orientation is desired for.
@@ -129,11 +129,11 @@ public class Quadric {
* Note that the interpretation of outward and inward depends on the quadric
* being drawn.
*
* @param orientation The orientation to set
*/
public void setOrientation(int orientation) {
this.orientation = orientation;
}
* @param orientation The orientation to set
*/
public void setOrientation(int orientation) {
this.orientation = orientation;
}
/**
* specifies if texture coordinates should be generated for
@@ -144,56 +144,53 @@ public class Quadric {
* The manner in which texture coordinates are generated depends upon the
* specific quadric rendered.
*
* @param textureFlag The textureFlag to set
*/
public void setTextureFlag(boolean textureFlag) {
this.textureFlag = textureFlag;
}
* @param textureFlag The textureFlag to set
*/
public void setTextureFlag(boolean textureFlag) {
this.textureFlag = textureFlag;
}
/**
* Returns the drawStyle.
* @return int
*/
public int getDrawStyle() {
return drawStyle;
}
/**
* Returns the drawStyle.
* @return int
*/
public int getDrawStyle() {
return drawStyle;
}
/**
* Returns the normals.
* @return int
*/
public int getNormals() {
return normals;
}
/**
* Returns the normals.
* @return int
*/
public int getNormals() {
return normals;
}
/**
* Returns the orientation.
* @return int
*/
public int getOrientation() {
return orientation;
}
/**
* Returns the orientation.
* @return int
*/
public int getOrientation() {
return orientation;
}
/**
* Returns the textureFlag.
* @return boolean
*/
public boolean getTextureFlag() {
return textureFlag;
}
/**
* Returns the textureFlag.
* @return boolean
*/
public boolean getTextureFlag() {
return textureFlag;
}
protected void TXTR_COORD(float x, float y) {
if (textureFlag) glTexCoord2f(x, y);
}
protected void TXTR_COORD(float x, float y) {
if (textureFlag) glTexCoord2f(x,y);
}
protected float sin(float r) {
return (float)Math.sin(r);
}
protected float cos(float r) {
return (float)Math.cos(r);
}
protected float sin(float r) {
return (float) Math.sin(r);
}
protected float cos(float r) {
return (float) Math.cos(r);
}
}
+30 -32
View File
@@ -1,4 +1,4 @@
/*
/*
* Copyright (c) 2002-2008 LWJGL Project
* All rights reserved.
*
@@ -42,39 +42,37 @@ import static org.lwjglx.util.glu.GLU.*;
*/
public class Registry extends Util {
private static final String versionString = "1.3";
private static final String extensionString =
"GLU_EXT_nurbs_tessellator " + "GLU_EXT_object_space_tess ";
private static final String versionString = "1.3";
private static final String extensionString = "GLU_EXT_nurbs_tessellator " + "GLU_EXT_object_space_tess ";
/**
* Method gluGetString
* @param name
* @return String
*/
public static String gluGetString(int name) {
/**
* Method gluGetString
* @param name
* @return String
*/
public static String gluGetString(int name) {
if (name == GLU_VERSION) {
return versionString;
} else if (name == GLU_EXTENSIONS) {
return extensionString;
}
return null;
}
if (name == GLU_VERSION) {
return versionString;
} else if (name == GLU_EXTENSIONS) {
return extensionString;
}
return null;
}
/**
* Method gluCheckExtension
*
* @param extName is an extension name.
* @param extString is a string of extensions separated by blank(s). There may or
* may not be leading or trailing blank(s) in extString.
* This works in cases of extensions being prefixes of another like
* GL_EXT_texture and GL_EXT_texture3D.
* @return boolean true if extName is found otherwise it returns false.
*/
public static boolean gluCheckExtension(String extName, String extString) {
if (extString == null || extName == null)
return false;
/**
* Method gluCheckExtension
*
* @param extName is an extension name.
* @param extString is a string of extensions separated by blank(s). There may or
* may not be leading or trailing blank(s) in extString.
* This works in cases of extensions being prefixes of another like
* GL_EXT_texture and GL_EXT_texture3D.
* @return boolean true if extName is found otherwise it returns false.
*/
public static boolean gluCheckExtension(String extName, String extString) {
if (extString == null || extName == null) return false;
return extString.indexOf(extName) != -1;
}
return extString.indexOf(extName) != -1;
}
}
+162 -173
View File
@@ -43,187 +43,176 @@ import static org.lwjglx.util.glu.GLU.*;
*/
public class Sphere extends Quadric {
/**
* Constructor
*/
public Sphere() {
super();
}
/**
* Constructor
*/
public Sphere() {
super();
}
/**
* draws a sphere of the given radius centered around the origin.
* The sphere is subdivided around the z axis into slices and along the z axis
* into stacks (similar to lines of longitude and latitude).
*
* If the orientation is set to GLU.OUTSIDE (with glu.quadricOrientation), then
* any normals generated point away from the center of the sphere. Otherwise,
* they point toward the center of the sphere.
/**
* draws a sphere of the given radius centered around the origin.
* The sphere is subdivided around the z axis into slices and along the z axis
* into stacks (similar to lines of longitude and latitude).
*
* If the orientation is set to GLU.OUTSIDE (with glu.quadricOrientation), then
* any normals generated point away from the center of the sphere. Otherwise,
* they point toward the center of the sphere.
*
* If texturing is turned on (with glu.quadricTexture), then texture
* coordinates are generated so that t ranges from 0.0 at z=-radius to 1.0 at
* z=radius (t increases linearly along longitudinal lines), and s ranges from
* 0.0 at the +y axis, to 0.25 at the +x axis, to 0.5 at the -y axis, to 0.75
* at the -x axis, and back to 1.0 at the +y axis.
*/
public void draw(float radius, int slices, int stacks) {
// TODO
* If texturing is turned on (with glu.quadricTexture), then texture
* coordinates are generated so that t ranges from 0.0 at z=-radius to 1.0 at
* z=radius (t increases linearly along longitudinal lines), and s ranges from
* 0.0 at the +y axis, to 0.25 at the +x axis, to 0.5 at the -y axis, to 0.75
* at the -x axis, and back to 1.0 at the +y axis.
*/
public void draw(float radius, int slices, int stacks) {
// TODO
float rho, drho, theta, dtheta;
float x, y, z;
float s, t, ds, dt;
int i, j, imin, imax;
boolean normals;
float nsign;
float rho, drho, theta, dtheta;
float x, y, z;
float s, t, ds, dt;
int i, j, imin, imax;
boolean normals;
float nsign;
normals = super.normals != GLU_NONE;
normals = super.normals != GLU_NONE;
if (super.orientation == GLU_INSIDE) {
nsign = -1.0f;
} else {
nsign = 1.0f;
}
if (super.orientation == GLU_INSIDE) {
nsign = -1.0f;
} else {
nsign = 1.0f;
}
drho = PI / stacks;
dtheta = 2.0f * PI / slices;
drho = PI / stacks;
dtheta = 2.0f * PI / slices;
if (super.drawStyle == GLU_FILL) {
if (!super.textureFlag) {
// draw +Z end as a triangle fan
glBegin(GL_TRIANGLE_FAN);
glNormal3f(0.0f, 0.0f, 1.0f);
glVertex3f(0.0f, 0.0f, nsign * radius);
for (j = 0; j <= slices; j++) {
theta = (j == slices) ? 0.0f : j * dtheta;
x = -sin(theta) * sin(drho);
y = cos(theta) * sin(drho);
z = nsign * cos(drho);
if (normals) {
glNormal3f(x * nsign, y * nsign, z * nsign);
}
glVertex3f(x * radius, y * radius, z * radius);
}
glEnd();
}
if (super.drawStyle == GLU_FILL) {
if (!super.textureFlag) {
// draw +Z end as a triangle fan
glBegin(GL_TRIANGLE_FAN);
glNormal3f(0.0f, 0.0f, 1.0f);
glVertex3f(0.0f, 0.0f, nsign * radius);
for (j = 0; j <= slices; j++) {
theta = (j == slices) ? 0.0f : j * dtheta;
x = -sin(theta) * sin(drho);
y = cos(theta) * sin(drho);
z = nsign * cos(drho);
if (normals) {
glNormal3f(x * nsign, y * nsign, z * nsign);
}
glVertex3f(x * radius, y * radius, z * radius);
}
glEnd();
}
ds = 1.0f / slices;
dt = 1.0f / stacks;
t = 1.0f; // because loop now runs from 0
if (super.textureFlag) {
imin = 0;
imax = stacks;
} else {
imin = 1;
imax = stacks - 1;
}
ds = 1.0f / slices;
dt = 1.0f / stacks;
t = 1.0f; // because loop now runs from 0
if (super.textureFlag) {
imin = 0;
imax = stacks;
} else {
imin = 1;
imax = stacks - 1;
}
// draw intermediate stacks as quad strips
for (i = imin; i < imax; i++) {
rho = i * drho;
glBegin(GL_QUAD_STRIP);
s = 0.0f;
for (j = 0; j <= slices; j++) {
theta = (j == slices) ? 0.0f : j * dtheta;
x = -sin(theta) * sin(rho);
y = cos(theta) * sin(rho);
z = nsign * cos(rho);
if (normals) {
glNormal3f(x * nsign, y * nsign, z * nsign);
}
TXTR_COORD(s, t);
glVertex3f(x * radius, y * radius, z * radius);
x = -sin(theta) * sin(rho + drho);
y = cos(theta) * sin(rho + drho);
z = nsign * cos(rho + drho);
if (normals) {
glNormal3f(x * nsign, y * nsign, z * nsign);
}
TXTR_COORD(s, t - dt);
s += ds;
glVertex3f(x * radius, y * radius, z * radius);
}
glEnd();
t -= dt;
}
// draw intermediate stacks as quad strips
for (i = imin; i < imax; i++) {
rho = i * drho;
glBegin(GL_QUAD_STRIP);
s = 0.0f;
for (j = 0; j <= slices; j++) {
theta = (j == slices) ? 0.0f : j * dtheta;
x = -sin(theta) * sin(rho);
y = cos(theta) * sin(rho);
z = nsign * cos(rho);
if (normals) {
glNormal3f(x * nsign, y * nsign, z * nsign);
}
TXTR_COORD(s, t);
glVertex3f(x * radius, y * radius, z * radius);
x = -sin(theta) * sin(rho + drho);
y = cos(theta) * sin(rho + drho);
z = nsign * cos(rho + drho);
if (normals) {
glNormal3f(x * nsign, y * nsign, z * nsign);
}
TXTR_COORD(s, t - dt);
s += ds;
glVertex3f(x * radius, y * radius, z * radius);
}
glEnd();
t -= dt;
}
if (!super.textureFlag) {
// draw -Z end as a triangle fan
glBegin(GL_TRIANGLE_FAN);
glNormal3f(0.0f, 0.0f, -1.0f);
glVertex3f(0.0f, 0.0f, -radius * nsign);
rho = PI - drho;
s = 1.0f;
for (j = slices; j >= 0; j--) {
theta = (j == slices) ? 0.0f : j * dtheta;
x = -sin(theta) * sin(rho);
y = cos(theta) * sin(rho);
z = nsign * cos(rho);
if (normals)
glNormal3f(x * nsign, y * nsign, z * nsign);
s -= ds;
glVertex3f(x * radius, y * radius, z * radius);
}
glEnd();
}
} else if (
super.drawStyle == GLU_LINE
|| super.drawStyle == GLU_SILHOUETTE) {
// draw stack lines
for (i = 1;
i < stacks;
i++) { // stack line at i==stacks-1 was missing here
rho = i * drho;
glBegin(GL_LINE_LOOP);
for (j = 0; j < slices; j++) {
theta = j * dtheta;
x = cos(theta) * sin(rho);
y = sin(theta) * sin(rho);
z = cos(rho);
if (normals)
glNormal3f(x * nsign, y * nsign, z * nsign);
glVertex3f(x * radius, y * radius, z * radius);
}
glEnd();
}
// draw slice lines
for (j = 0; j < slices; j++) {
theta = j * dtheta;
glBegin(GL_LINE_STRIP);
for (i = 0; i <= stacks; i++) {
rho = i * drho;
x = cos(theta) * sin(rho);
y = sin(theta) * sin(rho);
z = cos(rho);
if (normals)
glNormal3f(x * nsign, y * nsign, z * nsign);
glVertex3f(x * radius, y * radius, z * radius);
}
glEnd();
}
} else if (super.drawStyle == GLU_POINT) {
// top and bottom-most points
glBegin(GL_POINTS);
if (normals)
glNormal3f(0.0f, 0.0f, nsign);
glVertex3f(0.0f, 0.0f, radius);
if (normals)
glNormal3f(0.0f, 0.0f, -nsign);
glVertex3f(0.0f, 0.0f, -radius);
// loop over stacks
for (i = 1; i < stacks - 1; i++) {
rho = i * drho;
for (j = 0; j < slices; j++) {
theta = j * dtheta;
x = cos(theta) * sin(rho);
y = sin(theta) * sin(rho);
z = cos(rho);
if (normals)
glNormal3f(x * nsign, y * nsign, z * nsign);
glVertex3f(x * radius, y * radius, z * radius);
}
}
glEnd();
}
}
if (!super.textureFlag) {
// draw -Z end as a triangle fan
glBegin(GL_TRIANGLE_FAN);
glNormal3f(0.0f, 0.0f, -1.0f);
glVertex3f(0.0f, 0.0f, -radius * nsign);
rho = PI - drho;
s = 1.0f;
for (j = slices; j >= 0; j--) {
theta = (j == slices) ? 0.0f : j * dtheta;
x = -sin(theta) * sin(rho);
y = cos(theta) * sin(rho);
z = nsign * cos(rho);
if (normals) glNormal3f(x * nsign, y * nsign, z * nsign);
s -= ds;
glVertex3f(x * radius, y * radius, z * radius);
}
glEnd();
}
} else if (super.drawStyle == GLU_LINE || super.drawStyle == GLU_SILHOUETTE) {
// draw stack lines
for (i = 1; i < stacks; i++) { // stack line at i==stacks-1 was missing here
rho = i * drho;
glBegin(GL_LINE_LOOP);
for (j = 0; j < slices; j++) {
theta = j * dtheta;
x = cos(theta) * sin(rho);
y = sin(theta) * sin(rho);
z = cos(rho);
if (normals) glNormal3f(x * nsign, y * nsign, z * nsign);
glVertex3f(x * radius, y * radius, z * radius);
}
glEnd();
}
// draw slice lines
for (j = 0; j < slices; j++) {
theta = j * dtheta;
glBegin(GL_LINE_STRIP);
for (i = 0; i <= stacks; i++) {
rho = i * drho;
x = cos(theta) * sin(rho);
y = sin(theta) * sin(rho);
z = cos(rho);
if (normals) glNormal3f(x * nsign, y * nsign, z * nsign);
glVertex3f(x * radius, y * radius, z * radius);
}
glEnd();
}
} else if (super.drawStyle == GLU_POINT) {
// top and bottom-most points
glBegin(GL_POINTS);
if (normals) glNormal3f(0.0f, 0.0f, nsign);
glVertex3f(0.0f, 0.0f, radius);
if (normals) glNormal3f(0.0f, 0.0f, -nsign);
glVertex3f(0.0f, 0.0f, -radius);
// loop over stacks
for (i = 1; i < stacks - 1; i++) {
rho = i * drho;
for (j = 0; j < slices; j++) {
theta = j * dtheta;
x = cos(theta) * sin(rho);
y = sin(theta) * sin(rho);
z = cos(rho);
if (normals) glNormal3f(x * nsign, y * nsign, z * nsign);
glVertex3f(x * radius, y * radius, z * radius);
}
}
glEnd();
}
}
}
+179 -183
View File
@@ -31,13 +31,12 @@
*/
package org.lwjglx.util.glu;
import java.nio.IntBuffer;
import org.lwjgl.BufferUtils;
import static org.lwjgl.opengl.GL11.*;
import static org.lwjgl.opengl.GL12.*;
import java.nio.IntBuffer;
import org.lwjgl.BufferUtils;
/**
* Util.java
* <p/>
@@ -47,201 +46,198 @@ import static org.lwjgl.opengl.GL12.*;
* @author Erik Duijs
*/
public class Util {
/**
* temp IntBuffer of one for getting an int from some GL functions
*/
private static IntBuffer scratch = BufferUtils.createIntBuffer(16);
/**
* Return ceiling of integer division
*
* @param a
* @param b
*
* @return int
*/
protected static int ceil(int a, int b) {
return (a % b == 0 ? a / b : a / b + 1);
}
/**
* temp IntBuffer of one for getting an int from some GL functions
*/
private static IntBuffer scratch = BufferUtils.createIntBuffer(16);
/**
* Normalize vector
*
* @param v
*
* @return float[]
*/
protected static float[] normalize(float[] v) {
float r;
/**
* Return ceiling of integer division
*
* @param a
* @param b
*
* @return int
*/
protected static int ceil(int a, int b) {
return (a % b == 0 ? a / b : a / b + 1);
}
r = (float)Math.sqrt(v[0] * v[0] + v[1] * v[1] + v[2] * v[2]);
if ( r == 0.0 )
return v;
/**
* Normalize vector
*
* @param v
*
* @return float[]
*/
protected static float[] normalize(float[] v) {
float r;
r = 1.0f / r;
r = (float) Math.sqrt(v[0] * v[0] + v[1] * v[1] + v[2] * v[2]);
if (r == 0.0) return v;
v[0] *= r;
v[1] *= r;
v[2] *= r;
r = 1.0f / r;
return v;
}
v[0] *= r;
v[1] *= r;
v[2] *= r;
/**
* Calculate cross-product
*
* @param v1
* @param v2
* @param result
*/
protected static void cross(float[] v1, float[] v2, float[] result) {
result[0] = v1[1] * v2[2] - v1[2] * v2[1];
result[1] = v1[2] * v2[0] - v1[0] * v2[2];
result[2] = v1[0] * v2[1] - v1[1] * v2[0];
}
return v;
}
/**
* Method compPerPix.
*
* @param format
*
* @return int
*/
protected static int compPerPix(int format) {
/* Determine number of components per pixel */
switch ( format ) {
case GL_COLOR_INDEX:
case GL_STENCIL_INDEX:
case GL_DEPTH_COMPONENT:
case GL_RED:
case GL_GREEN:
case GL_BLUE:
case GL_ALPHA:
case GL_LUMINANCE:
return 1;
case GL_LUMINANCE_ALPHA:
return 2;
case GL_RGB:
case GL_BGR:
return 3;
case GL_RGBA:
case GL_BGRA:
return 4;
default :
return -1;
}
}
/**
* Calculate cross-product
*
* @param v1
* @param v2
* @param result
*/
protected static void cross(float[] v1, float[] v2, float[] result) {
result[0] = v1[1] * v2[2] - v1[2] * v2[1];
result[1] = v1[2] * v2[0] - v1[0] * v2[2];
result[2] = v1[0] * v2[1] - v1[1] * v2[0];
}
/**
* Method nearestPower.
* <p/>
* Compute the nearest power of 2 number. This algorithm is a little strange, but it works quite well.
*
* @param value
*
* @return int
*/
protected static int nearestPower(int value) {
int i;
/**
* Method compPerPix.
*
* @param format
*
* @return int
*/
protected static int compPerPix(int format) {
/* Determine number of components per pixel */
switch (format) {
case GL_COLOR_INDEX:
case GL_STENCIL_INDEX:
case GL_DEPTH_COMPONENT:
case GL_RED:
case GL_GREEN:
case GL_BLUE:
case GL_ALPHA:
case GL_LUMINANCE:
return 1;
case GL_LUMINANCE_ALPHA:
return 2;
case GL_RGB:
case GL_BGR:
return 3;
case GL_RGBA:
case GL_BGRA:
return 4;
default:
return -1;
}
}
i = 1;
/**
* Method nearestPower.
* <p/>
* Compute the nearest power of 2 number. This algorithm is a little strange, but it works quite well.
*
* @param value
*
* @return int
*/
protected static int nearestPower(int value) {
int i;
/* Error! */
if ( value == 0 )
return -1;
i = 1;
for ( ; ; ) {
if ( value == 1 ) {
return i;
} else if ( value == 3 ) {
return i << 2;
}
value >>= 1;
i <<= 1;
}
}
/* Error! */
if (value == 0) return -1;
/**
* Method bytesPerPixel.
*
* @param format
* @param type
*
* @return int
*/
protected static int bytesPerPixel(int format, int type) {
int n, m;
for (; ; ) {
if (value == 1) {
return i;
} else if (value == 3) {
return i << 2;
}
value >>= 1;
i <<= 1;
}
}
switch ( format ) {
case GL_COLOR_INDEX:
case GL_STENCIL_INDEX:
case GL_DEPTH_COMPONENT:
case GL_RED:
case GL_GREEN:
case GL_BLUE:
case GL_ALPHA:
case GL_LUMINANCE:
n = 1;
break;
case GL_LUMINANCE_ALPHA:
n = 2;
break;
case GL_RGB:
case GL_BGR:
n = 3;
break;
case GL_RGBA:
case GL_BGRA:
n = 4;
break;
default :
n = 0;
}
/**
* Method bytesPerPixel.
*
* @param format
* @param type
*
* @return int
*/
protected static int bytesPerPixel(int format, int type) {
int n, m;
switch ( type ) {
case GL_UNSIGNED_BYTE:
m = 1;
break;
case GL_BYTE:
m = 1;
break;
case GL_BITMAP:
m = 1;
break;
case GL_UNSIGNED_SHORT:
m = 2;
break;
case GL_SHORT:
m = 2;
break;
case GL_UNSIGNED_INT:
m = 4;
break;
case GL_INT:
m = 4;
break;
case GL_FLOAT:
m = 4;
break;
default :
m = 0;
}
switch (format) {
case GL_COLOR_INDEX:
case GL_STENCIL_INDEX:
case GL_DEPTH_COMPONENT:
case GL_RED:
case GL_GREEN:
case GL_BLUE:
case GL_ALPHA:
case GL_LUMINANCE:
n = 1;
break;
case GL_LUMINANCE_ALPHA:
n = 2;
break;
case GL_RGB:
case GL_BGR:
n = 3;
break;
case GL_RGBA:
case GL_BGRA:
n = 4;
break;
default:
n = 0;
}
return n * m;
}
switch (type) {
case GL_UNSIGNED_BYTE:
m = 1;
break;
case GL_BYTE:
m = 1;
break;
case GL_BITMAP:
m = 1;
break;
case GL_UNSIGNED_SHORT:
m = 2;
break;
case GL_SHORT:
m = 2;
break;
case GL_UNSIGNED_INT:
m = 4;
break;
case GL_INT:
m = 4;
break;
case GL_FLOAT:
m = 4;
break;
default:
m = 0;
}
/**
* Convenience method for returning an int, rather than getting it out of a buffer yourself.
*
* @param what
*
* @return int
*/
protected static int glGetIntegerv(int what) {
scratch.rewind();
glGetInteger(what, scratch);
return scratch.get();
}
return n * m;
}
/**
* Convenience method for returning an int, rather than getting it out of a buffer yourself.
*
* @param what
*
* @return int
*/
protected static int glGetIntegerv(int what) {
scratch.rewind();
glGetInteger(what, scratch);
return scratch.get();
}
}
@@ -31,70 +31,70 @@
*/
/*
* Portions Copyright (C) 2003-2006 Sun Microsystems, Inc.
* All rights reserved.
*/
* Portions Copyright (C) 2003-2006 Sun Microsystems, Inc.
* All rights reserved.
*/
/*
** License Applicability. Except to the extent portions of this file are
** made subject to an alternative license as permitted in the SGI Free
** Software License B, Version 1.1 (the "License"), the contents of this
** file are subject only to the provisions of the License. You may not use
** this file except in compliance with the License. You may obtain a copy
** of the License at Silicon Graphics, Inc., attn: Legal Services, 1600
** Amphitheatre Parkway, Mountain View, CA 94043-1351, or at:
**
** http://oss.sgi.com/projects/FreeB
**
** Note that, as provided in the License, the Software is distributed on an
** "AS IS" basis, with ALL EXPRESS AND IMPLIED WARRANTIES AND CONDITIONS
** DISCLAIMED, INCLUDING, WITHOUT LIMITATION, ANY IMPLIED WARRANTIES AND
** CONDITIONS OF MERCHANTABILITY, SATISFACTORY QUALITY, FITNESS FOR A
** PARTICULAR PURPOSE, AND NON-INFRINGEMENT.
**
** NOTE: The Original Code (as defined below) has been licensed to Sun
** Microsystems, Inc. ("Sun") under the SGI Free Software License B
** (Version 1.1), shown above ("SGI License"). Pursuant to Section
** 3.2(3) of the SGI License, Sun is distributing the Covered Code to
** you under an alternative license ("Alternative License"). This
** Alternative License includes all of the provisions of the SGI License
** except that Section 2.2 and 11 are omitted. Any differences between
** the Alternative License and the SGI License are offered solely by Sun
** and not by SGI.
**
** Original Code. The Original Code is: OpenGL Sample Implementation,
** Version 1.2.1, released January 26, 2000, developed by Silicon Graphics,
** Inc. The Original Code is Copyright (c) 1991-2000 Silicon Graphics, Inc.
** Copyright in any portions created by third parties is as indicated
** elsewhere herein. All Rights Reserved.
**
** Additional Notice Provisions: The application programming interfaces
** established by SGI in conjunction with the Original Code are The
** OpenGL(R) Graphics System: A Specification (Version 1.2.1), released
** April 1, 1999; The OpenGL(R) Graphics System Utility Library (Version
** 1.3), released November 4, 1998; and OpenGL(R) Graphics with the X
** Window System(R) (Version 1.3), released October 19, 1998. This software
** was created using the OpenGL(R) version 1.2.1 Sample Implementation
** published by SGI, but has not been independently verified as being
** compliant with the OpenGL(R) version 1.2.1 Specification.
**
** Author: Eric Veach, July 1994
** Java Port: Pepijn Van Eeckhoudt, July 2003
** Java Port: Nathan Parker Burg, August 2003
*/
** License Applicability. Except to the extent portions of this file are
** made subject to an alternative license as permitted in the SGI Free
** Software License B, Version 1.1 (the "License"), the contents of this
** file are subject only to the provisions of the License. You may not use
** this file except in compliance with the License. You may obtain a copy
** of the License at Silicon Graphics, Inc., attn: Legal Services, 1600
** Amphitheatre Parkway, Mountain View, CA 94043-1351, or at:
**
** http://oss.sgi.com/projects/FreeB
**
** Note that, as provided in the License, the Software is distributed on an
** "AS IS" basis, with ALL EXPRESS AND IMPLIED WARRANTIES AND CONDITIONS
** DISCLAIMED, INCLUDING, WITHOUT LIMITATION, ANY IMPLIED WARRANTIES AND
** CONDITIONS OF MERCHANTABILITY, SATISFACTORY QUALITY, FITNESS FOR A
** PARTICULAR PURPOSE, AND NON-INFRINGEMENT.
**
** NOTE: The Original Code (as defined below) has been licensed to Sun
** Microsystems, Inc. ("Sun") under the SGI Free Software License B
** (Version 1.1), shown above ("SGI License"). Pursuant to Section
** 3.2(3) of the SGI License, Sun is distributing the Covered Code to
** you under an alternative license ("Alternative License"). This
** Alternative License includes all of the provisions of the SGI License
** except that Section 2.2 and 11 are omitted. Any differences between
** the Alternative License and the SGI License are offered solely by Sun
** and not by SGI.
**
** Original Code. The Original Code is: OpenGL Sample Implementation,
** Version 1.2.1, released January 26, 2000, developed by Silicon Graphics,
** Inc. The Original Code is Copyright (c) 1991-2000 Silicon Graphics, Inc.
** Copyright in any portions created by third parties is as indicated
** elsewhere herein. All Rights Reserved.
**
** Additional Notice Provisions: The application programming interfaces
** established by SGI in conjunction with the Original Code are The
** OpenGL(R) Graphics System: A Specification (Version 1.2.1), released
** April 1, 1999; The OpenGL(R) Graphics System Utility Library (Version
** 1.3), released November 4, 1998; and OpenGL(R) Graphics with the X
** Window System(R) (Version 1.3), released October 19, 1998. This software
** was created using the OpenGL(R) version 1.2.1 Sample Implementation
** published by SGI, but has not been independently verified as being
** compliant with the OpenGL(R) version 1.2.1 Specification.
**
** Author: Eric Veach, July 1994
** Java Port: Pepijn Van Eeckhoudt, July 2003
** Java Port: Nathan Parker Burg, August 2003
*/
package org.lwjglx.util.glu.tessellation;
class ActiveRegion {
GLUhalfEdge eUp; /* upper edge, directed right to left */
DictNode nodeUp; /* dictionary node corresponding to eUp */
int windingNumber; /* used to determine which regions are
GLUhalfEdge eUp; /* upper edge, directed right to left */
DictNode nodeUp; /* dictionary node corresponding to eUp */
int windingNumber; /* used to determine which regions are
* inside the polygon */
boolean inside; /* is this region inside the polygon? */
boolean sentinel; /* marks fake edges at t = +/-infinity */
boolean dirty; /* marks regions where the upper or lower
boolean inside; /* is this region inside the polygon? */
boolean sentinel; /* marks fake edges at t = +/-infinity */
boolean dirty; /* marks regions where the upper or lower
* edge has changed, but we haven't checked
* whether they intersect yet */
boolean fixUpperEdge; /* marks temporary edges introduced when
boolean fixUpperEdge; /* marks temporary edges introduced when
* we process a "right vertex" (one without
* any edges leaving to the right) */
}
@@ -31,57 +31,57 @@
*/
/*
* Portions Copyright (C) 2003-2006 Sun Microsystems, Inc.
* All rights reserved.
*/
* Portions Copyright (C) 2003-2006 Sun Microsystems, Inc.
* All rights reserved.
*/
/*
** License Applicability. Except to the extent portions of this file are
** made subject to an alternative license as permitted in the SGI Free
** Software License B, Version 1.1 (the "License"), the contents of this
** file are subject only to the provisions of the License. You may not use
** this file except in compliance with the License. You may obtain a copy
** of the License at Silicon Graphics, Inc., attn: Legal Services, 1600
** Amphitheatre Parkway, Mountain View, CA 94043-1351, or at:
**
** http://oss.sgi.com/projects/FreeB
**
** Note that, as provided in the License, the Software is distributed on an
** "AS IS" basis, with ALL EXPRESS AND IMPLIED WARRANTIES AND CONDITIONS
** DISCLAIMED, INCLUDING, WITHOUT LIMITATION, ANY IMPLIED WARRANTIES AND
** CONDITIONS OF MERCHANTABILITY, SATISFACTORY QUALITY, FITNESS FOR A
** PARTICULAR PURPOSE, AND NON-INFRINGEMENT.
**
** NOTE: The Original Code (as defined below) has been licensed to Sun
** Microsystems, Inc. ("Sun") under the SGI Free Software License B
** (Version 1.1), shown above ("SGI License"). Pursuant to Section
** 3.2(3) of the SGI License, Sun is distributing the Covered Code to
** you under an alternative license ("Alternative License"). This
** Alternative License includes all of the provisions of the SGI License
** except that Section 2.2 and 11 are omitted. Any differences between
** the Alternative License and the SGI License are offered solely by Sun
** and not by SGI.
**
** Original Code. The Original Code is: OpenGL Sample Implementation,
** Version 1.2.1, released January 26, 2000, developed by Silicon Graphics,
** Inc. The Original Code is Copyright (c) 1991-2000 Silicon Graphics, Inc.
** Copyright in any portions created by third parties is as indicated
** elsewhere herein. All Rights Reserved.
**
** Additional Notice Provisions: The application programming interfaces
** established by SGI in conjunction with the Original Code are The
** OpenGL(R) Graphics System: A Specification (Version 1.2.1), released
** April 1, 1999; The OpenGL(R) Graphics System Utility Library (Version
** 1.3), released November 4, 1998; and OpenGL(R) Graphics with the X
** Window System(R) (Version 1.3), released October 19, 1998. This software
** was created using the OpenGL(R) version 1.2.1 Sample Implementation
** published by SGI, but has not been independently verified as being
** compliant with the OpenGL(R) version 1.2.1 Specification.
**
** Author: Eric Veach, July 1994
** Java Port: Pepijn Van Eeckhoudt, July 2003
** Java Port: Nathan Parker Burg, August 2003
*/
** License Applicability. Except to the extent portions of this file are
** made subject to an alternative license as permitted in the SGI Free
** Software License B, Version 1.1 (the "License"), the contents of this
** file are subject only to the provisions of the License. You may not use
** this file except in compliance with the License. You may obtain a copy
** of the License at Silicon Graphics, Inc., attn: Legal Services, 1600
** Amphitheatre Parkway, Mountain View, CA 94043-1351, or at:
**
** http://oss.sgi.com/projects/FreeB
**
** Note that, as provided in the License, the Software is distributed on an
** "AS IS" basis, with ALL EXPRESS AND IMPLIED WARRANTIES AND CONDITIONS
** DISCLAIMED, INCLUDING, WITHOUT LIMITATION, ANY IMPLIED WARRANTIES AND
** CONDITIONS OF MERCHANTABILITY, SATISFACTORY QUALITY, FITNESS FOR A
** PARTICULAR PURPOSE, AND NON-INFRINGEMENT.
**
** NOTE: The Original Code (as defined below) has been licensed to Sun
** Microsystems, Inc. ("Sun") under the SGI Free Software License B
** (Version 1.1), shown above ("SGI License"). Pursuant to Section
** 3.2(3) of the SGI License, Sun is distributing the Covered Code to
** you under an alternative license ("Alternative License"). This
** Alternative License includes all of the provisions of the SGI License
** except that Section 2.2 and 11 are omitted. Any differences between
** the Alternative License and the SGI License are offered solely by Sun
** and not by SGI.
**
** Original Code. The Original Code is: OpenGL Sample Implementation,
** Version 1.2.1, released January 26, 2000, developed by Silicon Graphics,
** Inc. The Original Code is Copyright (c) 1991-2000 Silicon Graphics, Inc.
** Copyright in any portions created by third parties is as indicated
** elsewhere herein. All Rights Reserved.
**
** Additional Notice Provisions: The application programming interfaces
** established by SGI in conjunction with the Original Code are The
** OpenGL(R) Graphics System: A Specification (Version 1.2.1), released
** April 1, 1999; The OpenGL(R) Graphics System Utility Library (Version
** 1.3), released November 4, 1998; and OpenGL(R) Graphics with the X
** Window System(R) (Version 1.3), released October 19, 1998. This software
** was created using the OpenGL(R) version 1.2.1 Sample Implementation
** published by SGI, but has not been independently verified as being
** compliant with the OpenGL(R) version 1.2.1 Specification.
**
** Author: Eric Veach, July 1994
** Java Port: Pepijn Van Eeckhoudt, July 2003
** Java Port: Nathan Parker Burg, August 2003
*/
package org.lwjglx.util.glu.tessellation;
class CachedVertex {
@@ -31,57 +31,57 @@
*/
/*
* Portions Copyright (C) 2003-2006 Sun Microsystems, Inc.
* All rights reserved.
*/
* Portions Copyright (C) 2003-2006 Sun Microsystems, Inc.
* All rights reserved.
*/
/*
** License Applicability. Except to the extent portions of this file are
** made subject to an alternative license as permitted in the SGI Free
** Software License B, Version 1.1 (the "License"), the contents of this
** file are subject only to the provisions of the License. You may not use
** this file except in compliance with the License. You may obtain a copy
** of the License at Silicon Graphics, Inc., attn: Legal Services, 1600
** Amphitheatre Parkway, Mountain View, CA 94043-1351, or at:
**
** http://oss.sgi.com/projects/FreeB
**
** Note that, as provided in the License, the Software is distributed on an
** "AS IS" basis, with ALL EXPRESS AND IMPLIED WARRANTIES AND CONDITIONS
** DISCLAIMED, INCLUDING, WITHOUT LIMITATION, ANY IMPLIED WARRANTIES AND
** CONDITIONS OF MERCHANTABILITY, SATISFACTORY QUALITY, FITNESS FOR A
** PARTICULAR PURPOSE, AND NON-INFRINGEMENT.
**
** NOTE: The Original Code (as defined below) has been licensed to Sun
** Microsystems, Inc. ("Sun") under the SGI Free Software License B
** (Version 1.1), shown above ("SGI License"). Pursuant to Section
** 3.2(3) of the SGI License, Sun is distributing the Covered Code to
** you under an alternative license ("Alternative License"). This
** Alternative License includes all of the provisions of the SGI License
** except that Section 2.2 and 11 are omitted. Any differences between
** the Alternative License and the SGI License are offered solely by Sun
** and not by SGI.
**
** Original Code. The Original Code is: OpenGL Sample Implementation,
** Version 1.2.1, released January 26, 2000, developed by Silicon Graphics,
** Inc. The Original Code is Copyright (c) 1991-2000 Silicon Graphics, Inc.
** Copyright in any portions created by third parties is as indicated
** elsewhere herein. All Rights Reserved.
**
** Additional Notice Provisions: The application programming interfaces
** established by SGI in conjunction with the Original Code are The
** OpenGL(R) Graphics System: A Specification (Version 1.2.1), released
** April 1, 1999; The OpenGL(R) Graphics System Utility Library (Version
** 1.3), released November 4, 1998; and OpenGL(R) Graphics with the X
** Window System(R) (Version 1.3), released October 19, 1998. This software
** was created using the OpenGL(R) version 1.2.1 Sample Implementation
** published by SGI, but has not been independently verified as being
** compliant with the OpenGL(R) version 1.2.1 Specification.
**
** Author: Eric Veach, July 1994
** Java Port: Pepijn Van Eeckhoudt, July 2003
** Java Port: Nathan Parker Burg, August 2003
*/
** License Applicability. Except to the extent portions of this file are
** made subject to an alternative license as permitted in the SGI Free
** Software License B, Version 1.1 (the "License"), the contents of this
** file are subject only to the provisions of the License. You may not use
** this file except in compliance with the License. You may obtain a copy
** of the License at Silicon Graphics, Inc., attn: Legal Services, 1600
** Amphitheatre Parkway, Mountain View, CA 94043-1351, or at:
**
** http://oss.sgi.com/projects/FreeB
**
** Note that, as provided in the License, the Software is distributed on an
** "AS IS" basis, with ALL EXPRESS AND IMPLIED WARRANTIES AND CONDITIONS
** DISCLAIMED, INCLUDING, WITHOUT LIMITATION, ANY IMPLIED WARRANTIES AND
** CONDITIONS OF MERCHANTABILITY, SATISFACTORY QUALITY, FITNESS FOR A
** PARTICULAR PURPOSE, AND NON-INFRINGEMENT.
**
** NOTE: The Original Code (as defined below) has been licensed to Sun
** Microsystems, Inc. ("Sun") under the SGI Free Software License B
** (Version 1.1), shown above ("SGI License"). Pursuant to Section
** 3.2(3) of the SGI License, Sun is distributing the Covered Code to
** you under an alternative license ("Alternative License"). This
** Alternative License includes all of the provisions of the SGI License
** except that Section 2.2 and 11 are omitted. Any differences between
** the Alternative License and the SGI License are offered solely by Sun
** and not by SGI.
**
** Original Code. The Original Code is: OpenGL Sample Implementation,
** Version 1.2.1, released January 26, 2000, developed by Silicon Graphics,
** Inc. The Original Code is Copyright (c) 1991-2000 Silicon Graphics, Inc.
** Copyright in any portions created by third parties is as indicated
** elsewhere herein. All Rights Reserved.
**
** Additional Notice Provisions: The application programming interfaces
** established by SGI in conjunction with the Original Code are The
** OpenGL(R) Graphics System: A Specification (Version 1.2.1), released
** April 1, 1999; The OpenGL(R) Graphics System Utility Library (Version
** 1.3), released November 4, 1998; and OpenGL(R) Graphics with the X
** Window System(R) (Version 1.3), released October 19, 1998. This software
** was created using the OpenGL(R) version 1.2.1 Sample Implementation
** published by SGI, but has not been independently verified as being
** compliant with the OpenGL(R) version 1.2.1 Specification.
**
** Author: Eric Veach, July 1994
** Java Port: Pepijn Van Eeckhoudt, July 2003
** Java Port: Nathan Parker Burg, August 2003
*/
package org.lwjglx.util.glu.tessellation;
class Dict {
@@ -89,8 +89,7 @@ class Dict {
Object frame;
DictLeq leq;
private Dict() {
}
private Dict() {}
static Dict dictNewDict(Object frame, DictLeq leq) {
Dict dict = new Dict();
@@ -31,57 +31,57 @@
*/
/*
* Portions Copyright (C) 2003-2006 Sun Microsystems, Inc.
* All rights reserved.
*/
* Portions Copyright (C) 2003-2006 Sun Microsystems, Inc.
* All rights reserved.
*/
/*
** License Applicability. Except to the extent portions of this file are
** made subject to an alternative license as permitted in the SGI Free
** Software License B, Version 1.1 (the "License"), the contents of this
** file are subject only to the provisions of the License. You may not use
** this file except in compliance with the License. You may obtain a copy
** of the License at Silicon Graphics, Inc., attn: Legal Services, 1600
** Amphitheatre Parkway, Mountain View, CA 94043-1351, or at:
**
** http://oss.sgi.com/projects/FreeB
**
** Note that, as provided in the License, the Software is distributed on an
** "AS IS" basis, with ALL EXPRESS AND IMPLIED WARRANTIES AND CONDITIONS
** DISCLAIMED, INCLUDING, WITHOUT LIMITATION, ANY IMPLIED WARRANTIES AND
** CONDITIONS OF MERCHANTABILITY, SATISFACTORY QUALITY, FITNESS FOR A
** PARTICULAR PURPOSE, AND NON-INFRINGEMENT.
**
** NOTE: The Original Code (as defined below) has been licensed to Sun
** Microsystems, Inc. ("Sun") under the SGI Free Software License B
** (Version 1.1), shown above ("SGI License"). Pursuant to Section
** 3.2(3) of the SGI License, Sun is distributing the Covered Code to
** you under an alternative license ("Alternative License"). This
** Alternative License includes all of the provisions of the SGI License
** except that Section 2.2 and 11 are omitted. Any differences between
** the Alternative License and the SGI License are offered solely by Sun
** and not by SGI.
**
** Original Code. The Original Code is: OpenGL Sample Implementation,
** Version 1.2.1, released January 26, 2000, developed by Silicon Graphics,
** Inc. The Original Code is Copyright (c) 1991-2000 Silicon Graphics, Inc.
** Copyright in any portions created by third parties is as indicated
** elsewhere herein. All Rights Reserved.
**
** Additional Notice Provisions: The application programming interfaces
** established by SGI in conjunction with the Original Code are The
** OpenGL(R) Graphics System: A Specification (Version 1.2.1), released
** April 1, 1999; The OpenGL(R) Graphics System Utility Library (Version
** 1.3), released November 4, 1998; and OpenGL(R) Graphics with the X
** Window System(R) (Version 1.3), released October 19, 1998. This software
** was created using the OpenGL(R) version 1.2.1 Sample Implementation
** published by SGI, but has not been independently verified as being
** compliant with the OpenGL(R) version 1.2.1 Specification.
**
** Author: Eric Veach, July 1994
** Java Port: Pepijn Van Eeckhoudt, July 2003
** Java Port: Nathan Parker Burg, August 2003
*/
** License Applicability. Except to the extent portions of this file are
** made subject to an alternative license as permitted in the SGI Free
** Software License B, Version 1.1 (the "License"), the contents of this
** file are subject only to the provisions of the License. You may not use
** this file except in compliance with the License. You may obtain a copy
** of the License at Silicon Graphics, Inc., attn: Legal Services, 1600
** Amphitheatre Parkway, Mountain View, CA 94043-1351, or at:
**
** http://oss.sgi.com/projects/FreeB
**
** Note that, as provided in the License, the Software is distributed on an
** "AS IS" basis, with ALL EXPRESS AND IMPLIED WARRANTIES AND CONDITIONS
** DISCLAIMED, INCLUDING, WITHOUT LIMITATION, ANY IMPLIED WARRANTIES AND
** CONDITIONS OF MERCHANTABILITY, SATISFACTORY QUALITY, FITNESS FOR A
** PARTICULAR PURPOSE, AND NON-INFRINGEMENT.
**
** NOTE: The Original Code (as defined below) has been licensed to Sun
** Microsystems, Inc. ("Sun") under the SGI Free Software License B
** (Version 1.1), shown above ("SGI License"). Pursuant to Section
** 3.2(3) of the SGI License, Sun is distributing the Covered Code to
** you under an alternative license ("Alternative License"). This
** Alternative License includes all of the provisions of the SGI License
** except that Section 2.2 and 11 are omitted. Any differences between
** the Alternative License and the SGI License are offered solely by Sun
** and not by SGI.
**
** Original Code. The Original Code is: OpenGL Sample Implementation,
** Version 1.2.1, released January 26, 2000, developed by Silicon Graphics,
** Inc. The Original Code is Copyright (c) 1991-2000 Silicon Graphics, Inc.
** Copyright in any portions created by third parties is as indicated
** elsewhere herein. All Rights Reserved.
**
** Additional Notice Provisions: The application programming interfaces
** established by SGI in conjunction with the Original Code are The
** OpenGL(R) Graphics System: A Specification (Version 1.2.1), released
** April 1, 1999; The OpenGL(R) Graphics System Utility Library (Version
** 1.3), released November 4, 1998; and OpenGL(R) Graphics with the X
** Window System(R) (Version 1.3), released October 19, 1998. This software
** was created using the OpenGL(R) version 1.2.1 Sample Implementation
** published by SGI, but has not been independently verified as being
** compliant with the OpenGL(R) version 1.2.1 Specification.
**
** Author: Eric Veach, July 1994
** Java Port: Pepijn Van Eeckhoudt, July 2003
** Java Port: Nathan Parker Burg, August 2003
*/
package org.lwjglx.util.glu.tessellation;
class DictNode {
@@ -31,67 +31,67 @@
*/
/*
* Portions Copyright (C) 2003-2006 Sun Microsystems, Inc.
* All rights reserved.
*/
* Portions Copyright (C) 2003-2006 Sun Microsystems, Inc.
* All rights reserved.
*/
/*
** License Applicability. Except to the extent portions of this file are
** made subject to an alternative license as permitted in the SGI Free
** Software License B, Version 1.1 (the "License"), the contents of this
** file are subject only to the provisions of the License. You may not use
** this file except in compliance with the License. You may obtain a copy
** of the License at Silicon Graphics, Inc., attn: Legal Services, 1600
** Amphitheatre Parkway, Mountain View, CA 94043-1351, or at:
**
** http://oss.sgi.com/projects/FreeB
**
** Note that, as provided in the License, the Software is distributed on an
** "AS IS" basis, with ALL EXPRESS AND IMPLIED WARRANTIES AND CONDITIONS
** DISCLAIMED, INCLUDING, WITHOUT LIMITATION, ANY IMPLIED WARRANTIES AND
** CONDITIONS OF MERCHANTABILITY, SATISFACTORY QUALITY, FITNESS FOR A
** PARTICULAR PURPOSE, AND NON-INFRINGEMENT.
**
** NOTE: The Original Code (as defined below) has been licensed to Sun
** Microsystems, Inc. ("Sun") under the SGI Free Software License B
** (Version 1.1), shown above ("SGI License"). Pursuant to Section
** 3.2(3) of the SGI License, Sun is distributing the Covered Code to
** you under an alternative license ("Alternative License"). This
** Alternative License includes all of the provisions of the SGI License
** except that Section 2.2 and 11 are omitted. Any differences between
** the Alternative License and the SGI License are offered solely by Sun
** and not by SGI.
**
** Original Code. The Original Code is: OpenGL Sample Implementation,
** Version 1.2.1, released January 26, 2000, developed by Silicon Graphics,
** Inc. The Original Code is Copyright (c) 1991-2000 Silicon Graphics, Inc.
** Copyright in any portions created by third parties is as indicated
** elsewhere herein. All Rights Reserved.
**
** Additional Notice Provisions: The application programming interfaces
** established by SGI in conjunction with the Original Code are The
** OpenGL(R) Graphics System: A Specification (Version 1.2.1), released
** April 1, 1999; The OpenGL(R) Graphics System Utility Library (Version
** 1.3), released November 4, 1998; and OpenGL(R) Graphics with the X
** Window System(R) (Version 1.3), released October 19, 1998. This software
** was created using the OpenGL(R) version 1.2.1 Sample Implementation
** published by SGI, but has not been independently verified as being
** compliant with the OpenGL(R) version 1.2.1 Specification.
**
** Author: Eric Veach, July 1994
** Java Port: Pepijn Van Eeckhoudt, July 2003
** Java Port: Nathan Parker Burg, August 2003
*/
** License Applicability. Except to the extent portions of this file are
** made subject to an alternative license as permitted in the SGI Free
** Software License B, Version 1.1 (the "License"), the contents of this
** file are subject only to the provisions of the License. You may not use
** this file except in compliance with the License. You may obtain a copy
** of the License at Silicon Graphics, Inc., attn: Legal Services, 1600
** Amphitheatre Parkway, Mountain View, CA 94043-1351, or at:
**
** http://oss.sgi.com/projects/FreeB
**
** Note that, as provided in the License, the Software is distributed on an
** "AS IS" basis, with ALL EXPRESS AND IMPLIED WARRANTIES AND CONDITIONS
** DISCLAIMED, INCLUDING, WITHOUT LIMITATION, ANY IMPLIED WARRANTIES AND
** CONDITIONS OF MERCHANTABILITY, SATISFACTORY QUALITY, FITNESS FOR A
** PARTICULAR PURPOSE, AND NON-INFRINGEMENT.
**
** NOTE: The Original Code (as defined below) has been licensed to Sun
** Microsystems, Inc. ("Sun") under the SGI Free Software License B
** (Version 1.1), shown above ("SGI License"). Pursuant to Section
** 3.2(3) of the SGI License, Sun is distributing the Covered Code to
** you under an alternative license ("Alternative License"). This
** Alternative License includes all of the provisions of the SGI License
** except that Section 2.2 and 11 are omitted. Any differences between
** the Alternative License and the SGI License are offered solely by Sun
** and not by SGI.
**
** Original Code. The Original Code is: OpenGL Sample Implementation,
** Version 1.2.1, released January 26, 2000, developed by Silicon Graphics,
** Inc. The Original Code is Copyright (c) 1991-2000 Silicon Graphics, Inc.
** Copyright in any portions created by third parties is as indicated
** elsewhere herein. All Rights Reserved.
**
** Additional Notice Provisions: The application programming interfaces
** established by SGI in conjunction with the Original Code are The
** OpenGL(R) Graphics System: A Specification (Version 1.2.1), released
** April 1, 1999; The OpenGL(R) Graphics System Utility Library (Version
** 1.3), released November 4, 1998; and OpenGL(R) Graphics with the X
** Window System(R) (Version 1.3), released October 19, 1998. This software
** was created using the OpenGL(R) version 1.2.1 Sample Implementation
** published by SGI, but has not been independently verified as being
** compliant with the OpenGL(R) version 1.2.1 Specification.
**
** Author: Eric Veach, July 1994
** Java Port: Pepijn Van Eeckhoudt, July 2003
** Java Port: Nathan Parker Burg, August 2003
*/
package org.lwjglx.util.glu.tessellation;
class GLUface {
public GLUface next; /* next face (never NULL) */
public GLUface prev; /* previous face (never NULL) */
public GLUhalfEdge anEdge; /* a half edge with this left face */
public Object data; /* room for client's data */
public GLUface next; /* next face (never NULL) */
public GLUface prev; /* previous face (never NULL) */
public GLUhalfEdge anEdge; /* a half edge with this left face */
public Object data; /* room for client's data */
/* Internal data (keep hidden) */
public GLUface trail; /* "stack" for conversion to strips */
public boolean marked; /* flag for conversion to strips */
public boolean inside; /* this face is in the polygon interior */
public GLUface trail; /* "stack" for conversion to strips */
public boolean marked; /* flag for conversion to strips */
public boolean inside; /* this face is in the polygon interior */
}
@@ -31,72 +31,70 @@
*/
/*
* Portions Copyright (C) 2003-2006 Sun Microsystems, Inc.
* All rights reserved.
*/
* Portions Copyright (C) 2003-2006 Sun Microsystems, Inc.
* All rights reserved.
*/
/*
** License Applicability. Except to the extent portions of this file are
** made subject to an alternative license as permitted in the SGI Free
** Software License B, Version 1.1 (the "License"), the contents of this
** file are subject only to the provisions of the License. You may not use
** this file except in compliance with the License. You may obtain a copy
** of the License at Silicon Graphics, Inc., attn: Legal Services, 1600
** Amphitheatre Parkway, Mountain View, CA 94043-1351, or at:
**
** http://oss.sgi.com/projects/FreeB
**
** Note that, as provided in the License, the Software is distributed on an
** "AS IS" basis, with ALL EXPRESS AND IMPLIED WARRANTIES AND CONDITIONS
** DISCLAIMED, INCLUDING, WITHOUT LIMITATION, ANY IMPLIED WARRANTIES AND
** CONDITIONS OF MERCHANTABILITY, SATISFACTORY QUALITY, FITNESS FOR A
** PARTICULAR PURPOSE, AND NON-INFRINGEMENT.
**
** NOTE: The Original Code (as defined below) has been licensed to Sun
** Microsystems, Inc. ("Sun") under the SGI Free Software License B
** (Version 1.1), shown above ("SGI License"). Pursuant to Section
** 3.2(3) of the SGI License, Sun is distributing the Covered Code to
** you under an alternative license ("Alternative License"). This
** Alternative License includes all of the provisions of the SGI License
** except that Section 2.2 and 11 are omitted. Any differences between
** the Alternative License and the SGI License are offered solely by Sun
** and not by SGI.
**
** Original Code. The Original Code is: OpenGL Sample Implementation,
** Version 1.2.1, released January 26, 2000, developed by Silicon Graphics,
** Inc. The Original Code is Copyright (c) 1991-2000 Silicon Graphics, Inc.
** Copyright in any portions created by third parties is as indicated
** elsewhere herein. All Rights Reserved.
**
** Additional Notice Provisions: The application programming interfaces
** established by SGI in conjunction with the Original Code are The
** OpenGL(R) Graphics System: A Specification (Version 1.2.1), released
** April 1, 1999; The OpenGL(R) Graphics System Utility Library (Version
** 1.3), released November 4, 1998; and OpenGL(R) Graphics with the X
** Window System(R) (Version 1.3), released October 19, 1998. This software
** was created using the OpenGL(R) version 1.2.1 Sample Implementation
** published by SGI, but has not been independently verified as being
** compliant with the OpenGL(R) version 1.2.1 Specification.
**
** Author: Eric Veach, July 1994
** Java Port: Pepijn Van Eeckhoudt, July 2003
** Java Port: Nathan Parker Burg, August 2003
*/
** License Applicability. Except to the extent portions of this file are
** made subject to an alternative license as permitted in the SGI Free
** Software License B, Version 1.1 (the "License"), the contents of this
** file are subject only to the provisions of the License. You may not use
** this file except in compliance with the License. You may obtain a copy
** of the License at Silicon Graphics, Inc., attn: Legal Services, 1600
** Amphitheatre Parkway, Mountain View, CA 94043-1351, or at:
**
** http://oss.sgi.com/projects/FreeB
**
** Note that, as provided in the License, the Software is distributed on an
** "AS IS" basis, with ALL EXPRESS AND IMPLIED WARRANTIES AND CONDITIONS
** DISCLAIMED, INCLUDING, WITHOUT LIMITATION, ANY IMPLIED WARRANTIES AND
** CONDITIONS OF MERCHANTABILITY, SATISFACTORY QUALITY, FITNESS FOR A
** PARTICULAR PURPOSE, AND NON-INFRINGEMENT.
**
** NOTE: The Original Code (as defined below) has been licensed to Sun
** Microsystems, Inc. ("Sun") under the SGI Free Software License B
** (Version 1.1), shown above ("SGI License"). Pursuant to Section
** 3.2(3) of the SGI License, Sun is distributing the Covered Code to
** you under an alternative license ("Alternative License"). This
** Alternative License includes all of the provisions of the SGI License
** except that Section 2.2 and 11 are omitted. Any differences between
** the Alternative License and the SGI License are offered solely by Sun
** and not by SGI.
**
** Original Code. The Original Code is: OpenGL Sample Implementation,
** Version 1.2.1, released January 26, 2000, developed by Silicon Graphics,
** Inc. The Original Code is Copyright (c) 1991-2000 Silicon Graphics, Inc.
** Copyright in any portions created by third parties is as indicated
** elsewhere herein. All Rights Reserved.
**
** Additional Notice Provisions: The application programming interfaces
** established by SGI in conjunction with the Original Code are The
** OpenGL(R) Graphics System: A Specification (Version 1.2.1), released
** April 1, 1999; The OpenGL(R) Graphics System Utility Library (Version
** 1.3), released November 4, 1998; and OpenGL(R) Graphics with the X
** Window System(R) (Version 1.3), released October 19, 1998. This software
** was created using the OpenGL(R) version 1.2.1 Sample Implementation
** published by SGI, but has not been independently verified as being
** compliant with the OpenGL(R) version 1.2.1 Specification.
**
** Author: Eric Veach, July 1994
** Java Port: Pepijn Van Eeckhoudt, July 2003
** Java Port: Nathan Parker Burg, August 2003
*/
package org.lwjglx.util.glu.tessellation;
class GLUhalfEdge {
public GLUhalfEdge next; /* doubly-linked list (prev==Sym->next) */
public GLUhalfEdge Sym; /* same edge, opposite direction */
public GLUhalfEdge Onext; /* next edge CCW around origin */
public GLUhalfEdge Lnext; /* next edge CCW around left face */
public GLUvertex Org; /* origin vertex (Overtex too long) */
public GLUface Lface; /* left face */
public GLUhalfEdge next; /* doubly-linked list (prev==Sym->next) */
public GLUhalfEdge Sym; /* same edge, opposite direction */
public GLUhalfEdge Onext; /* next edge CCW around origin */
public GLUhalfEdge Lnext; /* next edge CCW around left face */
public GLUvertex Org; /* origin vertex (Overtex too long) */
public GLUface Lface; /* left face */
/* Internal data (keep hidden) */
public ActiveRegion activeRegion; /* a region with this upper edge (sweep.c) */
public int winding; /* change in winding number when crossing */
public ActiveRegion activeRegion; /* a region with this upper edge (sweep.c) */
public int winding; /* change in winding number when crossing */
public boolean first;
GLUhalfEdge(boolean first) {
@@ -31,64 +31,62 @@
*/
/*
* Portions Copyright (C) 2003-2006 Sun Microsystems, Inc.
* All rights reserved.
*/
* Portions Copyright (C) 2003-2006 Sun Microsystems, Inc.
* All rights reserved.
*/
/*
** License Applicability. Except to the extent portions of this file are
** made subject to an alternative license as permitted in the SGI Free
** Software License B, Version 1.1 (the "License"), the contents of this
** file are subject only to the provisions of the License. You may not use
** this file except in compliance with the License. You may obtain a copy
** of the License at Silicon Graphics, Inc., attn: Legal Services, 1600
** Amphitheatre Parkway, Mountain View, CA 94043-1351, or at:
**
** http://oss.sgi.com/projects/FreeB
**
** Note that, as provided in the License, the Software is distributed on an
** "AS IS" basis, with ALL EXPRESS AND IMPLIED WARRANTIES AND CONDITIONS
** DISCLAIMED, INCLUDING, WITHOUT LIMITATION, ANY IMPLIED WARRANTIES AND
** CONDITIONS OF MERCHANTABILITY, SATISFACTORY QUALITY, FITNESS FOR A
** PARTICULAR PURPOSE, AND NON-INFRINGEMENT.
**
** NOTE: The Original Code (as defined below) has been licensed to Sun
** Microsystems, Inc. ("Sun") under the SGI Free Software License B
** (Version 1.1), shown above ("SGI License"). Pursuant to Section
** 3.2(3) of the SGI License, Sun is distributing the Covered Code to
** you under an alternative license ("Alternative License"). This
** Alternative License includes all of the provisions of the SGI License
** except that Section 2.2 and 11 are omitted. Any differences between
** the Alternative License and the SGI License are offered solely by Sun
** and not by SGI.
**
** Original Code. The Original Code is: OpenGL Sample Implementation,
** Version 1.2.1, released January 26, 2000, developed by Silicon Graphics,
** Inc. The Original Code is Copyright (c) 1991-2000 Silicon Graphics, Inc.
** Copyright in any portions created by third parties is as indicated
** elsewhere herein. All Rights Reserved.
**
** Additional Notice Provisions: The application programming interfaces
** established by SGI in conjunction with the Original Code are The
** OpenGL(R) Graphics System: A Specification (Version 1.2.1), released
** April 1, 1999; The OpenGL(R) Graphics System Utility Library (Version
** 1.3), released November 4, 1998; and OpenGL(R) Graphics with the X
** Window System(R) (Version 1.3), released October 19, 1998. This software
** was created using the OpenGL(R) version 1.2.1 Sample Implementation
** published by SGI, but has not been independently verified as being
** compliant with the OpenGL(R) version 1.2.1 Specification.
**
** Author: Eric Veach, July 1994
** Java Port: Pepijn Van Eeckhoudt, July 2003
** Java Port: Nathan Parker Burg, August 2003
*/
** License Applicability. Except to the extent portions of this file are
** made subject to an alternative license as permitted in the SGI Free
** Software License B, Version 1.1 (the "License"), the contents of this
** file are subject only to the provisions of the License. You may not use
** this file except in compliance with the License. You may obtain a copy
** of the License at Silicon Graphics, Inc., attn: Legal Services, 1600
** Amphitheatre Parkway, Mountain View, CA 94043-1351, or at:
**
** http://oss.sgi.com/projects/FreeB
**
** Note that, as provided in the License, the Software is distributed on an
** "AS IS" basis, with ALL EXPRESS AND IMPLIED WARRANTIES AND CONDITIONS
** DISCLAIMED, INCLUDING, WITHOUT LIMITATION, ANY IMPLIED WARRANTIES AND
** CONDITIONS OF MERCHANTABILITY, SATISFACTORY QUALITY, FITNESS FOR A
** PARTICULAR PURPOSE, AND NON-INFRINGEMENT.
**
** NOTE: The Original Code (as defined below) has been licensed to Sun
** Microsystems, Inc. ("Sun") under the SGI Free Software License B
** (Version 1.1), shown above ("SGI License"). Pursuant to Section
** 3.2(3) of the SGI License, Sun is distributing the Covered Code to
** you under an alternative license ("Alternative License"). This
** Alternative License includes all of the provisions of the SGI License
** except that Section 2.2 and 11 are omitted. Any differences between
** the Alternative License and the SGI License are offered solely by Sun
** and not by SGI.
**
** Original Code. The Original Code is: OpenGL Sample Implementation,
** Version 1.2.1, released January 26, 2000, developed by Silicon Graphics,
** Inc. The Original Code is Copyright (c) 1991-2000 Silicon Graphics, Inc.
** Copyright in any portions created by third parties is as indicated
** elsewhere herein. All Rights Reserved.
**
** Additional Notice Provisions: The application programming interfaces
** established by SGI in conjunction with the Original Code are The
** OpenGL(R) Graphics System: A Specification (Version 1.2.1), released
** April 1, 1999; The OpenGL(R) Graphics System Utility Library (Version
** 1.3), released November 4, 1998; and OpenGL(R) Graphics with the X
** Window System(R) (Version 1.3), released October 19, 1998. This software
** was created using the OpenGL(R) version 1.2.1 Sample Implementation
** published by SGI, but has not been independently verified as being
** compliant with the OpenGL(R) version 1.2.1 Specification.
**
** Author: Eric Veach, July 1994
** Java Port: Pepijn Van Eeckhoudt, July 2003
** Java Port: Nathan Parker Burg, August 2003
*/
package org.lwjglx.util.glu.tessellation;
class GLUmesh {
GLUvertex vHead = new GLUvertex(); /* dummy header for vertex list */
GLUface fHead = new GLUface(); /* dummy header for face list */
GLUhalfEdge eHead = new GLUhalfEdge(true); /* dummy header for edge list */
GLUhalfEdge eHeadSym = new GLUhalfEdge(false); /* and its symmetric counterpart */
GLUvertex vHead = new GLUvertex(); /* dummy header for vertex list */
GLUface fHead = new GLUface(); /* dummy header for face list */
GLUhalfEdge eHead = new GLUhalfEdge(true); /* dummy header for edge list */
GLUhalfEdge eHeadSym = new GLUhalfEdge(false); /* and its symmetric counterpart */
}
@@ -31,113 +31,111 @@
*/
/*
* Portions Copyright (C) 2003-2006 Sun Microsystems, Inc.
* All rights reserved.
*/
* Portions Copyright (C) 2003-2006 Sun Microsystems, Inc.
* All rights reserved.
*/
/*
** License Applicability. Except to the extent portions of this file are
** made subject to an alternative license as permitted in the SGI Free
** Software License B, Version 1.1 (the "License"), the contents of this
** file are subject only to the provisions of the License. You may not use
** this file except in compliance with the License. You may obtain a copy
** of the License at Silicon Graphics, Inc., attn: Legal Services, 1600
** Amphitheatre Parkway, Mountain View, CA 94043-1351, or at:
**
** http://oss.sgi.com/projects/FreeB
**
** Note that, as provided in the License, the Software is distributed on an
** "AS IS" basis, with ALL EXPRESS AND IMPLIED WARRANTIES AND CONDITIONS
** DISCLAIMED, INCLUDING, WITHOUT LIMITATION, ANY IMPLIED WARRANTIES AND
** CONDITIONS OF MERCHANTABILITY, SATISFACTORY QUALITY, FITNESS FOR A
** PARTICULAR PURPOSE, AND NON-INFRINGEMENT.
**
** NOTE: The Original Code (as defined below) has been licensed to Sun
** Microsystems, Inc. ("Sun") under the SGI Free Software License B
** (Version 1.1), shown above ("SGI License"). Pursuant to Section
** 3.2(3) of the SGI License, Sun is distributing the Covered Code to
** you under an alternative license ("Alternative License"). This
** Alternative License includes all of the provisions of the SGI License
** except that Section 2.2 and 11 are omitted. Any differences between
** the Alternative License and the SGI License are offered solely by Sun
** and not by SGI.
**
** Original Code. The Original Code is: OpenGL Sample Implementation,
** Version 1.2.1, released January 26, 2000, developed by Silicon Graphics,
** Inc. The Original Code is Copyright (c) 1991-2000 Silicon Graphics, Inc.
** Copyright in any portions created by third parties is as indicated
** elsewhere herein. All Rights Reserved.
**
** Additional Notice Provisions: The application programming interfaces
** established by SGI in conjunction with the Original Code are The
** OpenGL(R) Graphics System: A Specification (Version 1.2.1), released
** April 1, 1999; The OpenGL(R) Graphics System Utility Library (Version
** 1.3), released November 4, 1998; and OpenGL(R) Graphics with the X
** Window System(R) (Version 1.3), released October 19, 1998. This software
** was created using the OpenGL(R) version 1.2.1 Sample Implementation
** published by SGI, but has not been independently verified as being
** compliant with the OpenGL(R) version 1.2.1 Specification.
**
** Author: Eric Veach, July 1994
** Java Port: Pepijn Van Eeckhoudt, July 2003
** Java Port: Nathan Parker Burg, August 2003
*/
** License Applicability. Except to the extent portions of this file are
** made subject to an alternative license as permitted in the SGI Free
** Software License B, Version 1.1 (the "License"), the contents of this
** file are subject only to the provisions of the License. You may not use
** this file except in compliance with the License. You may obtain a copy
** of the License at Silicon Graphics, Inc., attn: Legal Services, 1600
** Amphitheatre Parkway, Mountain View, CA 94043-1351, or at:
**
** http://oss.sgi.com/projects/FreeB
**
** Note that, as provided in the License, the Software is distributed on an
** "AS IS" basis, with ALL EXPRESS AND IMPLIED WARRANTIES AND CONDITIONS
** DISCLAIMED, INCLUDING, WITHOUT LIMITATION, ANY IMPLIED WARRANTIES AND
** CONDITIONS OF MERCHANTABILITY, SATISFACTORY QUALITY, FITNESS FOR A
** PARTICULAR PURPOSE, AND NON-INFRINGEMENT.
**
** NOTE: The Original Code (as defined below) has been licensed to Sun
** Microsystems, Inc. ("Sun") under the SGI Free Software License B
** (Version 1.1), shown above ("SGI License"). Pursuant to Section
** 3.2(3) of the SGI License, Sun is distributing the Covered Code to
** you under an alternative license ("Alternative License"). This
** Alternative License includes all of the provisions of the SGI License
** except that Section 2.2 and 11 are omitted. Any differences between
** the Alternative License and the SGI License are offered solely by Sun
** and not by SGI.
**
** Original Code. The Original Code is: OpenGL Sample Implementation,
** Version 1.2.1, released January 26, 2000, developed by Silicon Graphics,
** Inc. The Original Code is Copyright (c) 1991-2000 Silicon Graphics, Inc.
** Copyright in any portions created by third parties is as indicated
** elsewhere herein. All Rights Reserved.
**
** Additional Notice Provisions: The application programming interfaces
** established by SGI in conjunction with the Original Code are The
** OpenGL(R) Graphics System: A Specification (Version 1.2.1), released
** April 1, 1999; The OpenGL(R) Graphics System Utility Library (Version
** 1.3), released November 4, 1998; and OpenGL(R) Graphics with the X
** Window System(R) (Version 1.3), released October 19, 1998. This software
** was created using the OpenGL(R) version 1.2.1 Sample Implementation
** published by SGI, but has not been independently verified as being
** compliant with the OpenGL(R) version 1.2.1 Specification.
**
** Author: Eric Veach, July 1994
** Java Port: Pepijn Van Eeckhoudt, July 2003
** Java Port: Nathan Parker Burg, August 2003
*/
package org.lwjglx.util.glu.tessellation;
import static org.lwjglx.util.glu.GLU.*;
import org.lwjglx.util.glu.GLUtessellator;
import org.lwjglx.util.glu.GLUtessellatorCallback;
import org.lwjglx.util.glu.GLUtessellatorCallbackAdapter;
import static org.lwjglx.util.glu.GLU.*;
public class GLUtessellatorImpl implements GLUtessellator {
public static final int TESS_MAX_CACHE = 100;
private int state; /* what begin/end calls have we seen? */
private int state; /* what begin/end calls have we seen? */
private GLUhalfEdge lastEdge; /* lastEdge->Org is the most recent vertex */
GLUmesh mesh; /* stores the input contours, and eventually
private GLUhalfEdge lastEdge; /* lastEdge->Org is the most recent vertex */
GLUmesh mesh; /* stores the input contours, and eventually
the tessellation itself */
/*** state needed for projecting onto the sweep plane ***/
double[] normal = new double[3]; /* user-specified normal (if provided) */
double[] normal = new double[3]; /* user-specified normal (if provided) */
double[] sUnit = new double[3]; /* unit vector in s-direction (debugging) */
double[] tUnit = new double[3]; /* unit vector in t-direction (debugging) */
double[] sUnit = new double[3]; /* unit vector in s-direction (debugging) */
double[] tUnit = new double[3]; /* unit vector in t-direction (debugging) */
/*** state needed for the line sweep ***/
private double relTolerance; /* tolerance for merging features */
private double relTolerance; /* tolerance for merging features */
int windingRule; /* rule for determining polygon interior */
boolean fatalError; /* fatal error: needed combine callback */
int windingRule; /* rule for determining polygon interior */
boolean fatalError; /* fatal error: needed combine callback */
Dict dict; /* edge dictionary for sweep line */
PriorityQ pq; /* priority queue of vertex events */
GLUvertex event; /* current sweep event being processed */
Dict dict; /* edge dictionary for sweep line */
PriorityQ pq; /* priority queue of vertex events */
GLUvertex event; /* current sweep event being processed */
/*** state needed for rendering callbacks (see render.c) ***/
boolean flagBoundary; /* mark boundary edges (use EdgeFlag) */
boolean flagBoundary; /* mark boundary edges (use EdgeFlag) */
boolean boundaryOnly; /* Extract contours, not triangles */
boolean boundaryOnly; /* Extract contours, not triangles */
GLUface lonelyTriList;
/* list of triangles which could not be rendered as strips or fans */
/*** state needed to cache single-contour polygons for renderCache() */
private boolean flushCacheOnNextVertex; /* empty cache on next vertex() call */
private boolean flushCacheOnNextVertex; /* empty cache on next vertex() call */
int cacheCount; /* number of cached vertices */
CachedVertex[] cache = new CachedVertex[TESS_MAX_CACHE]; /* the vertex data */
int cacheCount; /* number of cached vertices */
CachedVertex[] cache = new CachedVertex[TESS_MAX_CACHE]; /* the vertex data */
/*** rendering callbacks that also pass polygon data ***/
private Object polygonData; /* client data for current polygon */
private Object polygonData; /* client data for current polygon */
private GLUtessellatorCallback callBegin;
private GLUtessellatorCallback callEdgeFlag;
private GLUtessellatorCallback callVertex;
private GLUtessellatorCallback callEnd;
// private GLUtessellatorCallback callMesh;
// private GLUtessellatorCallback callMesh;
private GLUtessellatorCallback callError;
private GLUtessellatorCallback callCombine;
@@ -145,16 +143,16 @@ public class GLUtessellatorImpl implements GLUtessellator {
private GLUtessellatorCallback callEdgeFlagData;
private GLUtessellatorCallback callVertexData;
private GLUtessellatorCallback callEndData;
// private GLUtessellatorCallback callMeshData;
// private GLUtessellatorCallback callMeshData;
private GLUtessellatorCallback callErrorData;
private GLUtessellatorCallback callCombineData;
private static final double GLU_TESS_DEFAULT_TOLERANCE = 0.0;
// private static final int GLU_TESS_MESH = 100112; /* void (*)(GLUmesh *mesh) */
// private static final int GLU_TESS_MESH = 100112; /* void (*)(GLUmesh *mesh) */
private static GLUtessellatorCallback NULL_CB = new GLUtessellatorCallbackAdapter();
// #define MAX_FAST_ALLOC (MAX(sizeof(EdgePair), \
// MAX(sizeof(GLUvertex),sizeof(GLUface))))
// #define MAX_FAST_ALLOC (MAX(sizeof(EdgePair), \
// MAX(sizeof(GLUvertex),sizeof(GLUface))))
public GLUtessellatorImpl() {
state = TessState.T_DORMANT;
@@ -174,7 +172,7 @@ public class GLUtessellatorImpl implements GLUtessellator {
callEnd = NULL_CB;
callError = NULL_CB;
callCombine = NULL_CB;
// callMesh = NULL_CB;
// callMesh = NULL_CB;
callBeginData = NULL_CB;
callEdgeFlagData = NULL_CB;
@@ -190,12 +188,10 @@ public class GLUtessellatorImpl implements GLUtessellator {
}
}
public static GLUtessellator gluNewTess()
{
public static GLUtessellator gluNewTess() {
return new GLUtessellatorImpl();
}
private void makeDormant() {
/* Return the tessellator to its original dormant state. */
@@ -250,7 +246,7 @@ public class GLUtessellatorImpl implements GLUtessellator {
case GLU_TESS_WINDING_RULE:
int windingRule = (int) value;
if (windingRule != value) break; /* not an integer */
if (windingRule != value) break; /* not an integer */
switch (windingRule) {
case GLU_TESS_WINDING_ODD:
@@ -275,20 +271,20 @@ public class GLUtessellatorImpl implements GLUtessellator {
callErrorOrErrorData(GLU_INVALID_VALUE);
}
/* Returns tessellator property */
/* Returns tessellator property */
public void gluGetTessProperty(int which, double[] value, int value_offset) {
switch (which) {
case GLU_TESS_TOLERANCE:
/* tolerance should be in range [0..1] */
/* tolerance should be in range [0..1] */
assert (0.0 <= relTolerance && relTolerance <= 1.0);
value[value_offset] = relTolerance;
break;
case GLU_TESS_WINDING_RULE:
assert (windingRule == GLU_TESS_WINDING_ODD ||
windingRule == GLU_TESS_WINDING_NONZERO ||
windingRule == GLU_TESS_WINDING_POSITIVE ||
windingRule == GLU_TESS_WINDING_NEGATIVE ||
windingRule == GLU_TESS_WINDING_ABS_GEQ_TWO);
assert (windingRule == GLU_TESS_WINDING_ODD
|| windingRule == GLU_TESS_WINDING_NONZERO
|| windingRule == GLU_TESS_WINDING_POSITIVE
|| windingRule == GLU_TESS_WINDING_NEGATIVE
|| windingRule == GLU_TESS_WINDING_ABS_GEQ_TWO);
value[value_offset] = windingRule;
break;
case GLU_TESS_BOUNDARY_ONLY:
@@ -318,16 +314,16 @@ public class GLUtessellatorImpl implements GLUtessellator {
return;
case GLU_TESS_EDGE_FLAG:
callEdgeFlag = aCallback == null ? NULL_CB : aCallback;
/* If the client wants boundary edges to be flagged,
* we render everything as separate triangles (no strips or fans).
*/
/* If the client wants boundary edges to be flagged,
* we render everything as separate triangles (no strips or fans).
*/
flagBoundary = aCallback != null;
return;
case GLU_TESS_EDGE_FLAG_DATA:
callEdgeFlagData = callBegin = aCallback == null ? NULL_CB : aCallback;
/* If the client wants boundary edges to be flagged,
* we render everything as separate triangles (no strips or fans).
*/
/* If the client wants boundary edges to be flagged,
* we render everything as separate triangles (no strips or fans).
*/
flagBoundary = (aCallback != null);
return;
case GLU_TESS_VERTEX:
@@ -354,9 +350,9 @@ public class GLUtessellatorImpl implements GLUtessellator {
case GLU_TESS_COMBINE_DATA:
callCombineData = aCallback == null ? NULL_CB : aCallback;
return;
// case GLU_TESS_MESH:
// callMesh = aCallback == null ? NULL_CB : aCallback;
// return;
// case GLU_TESS_MESH:
// callMesh = aCallback == null ? NULL_CB : aCallback;
// return;
default:
callErrorOrErrorData(GLU_INVALID_ENUM);
return;
@@ -368,30 +364,30 @@ public class GLUtessellatorImpl implements GLUtessellator {
e = lastEdge;
if (e == null) {
/* Make a self-loop (one vertex, one edge). */
/* Make a self-loop (one vertex, one edge). */
e = Mesh.__gl_meshMakeEdge(mesh);
if (e == null) return false;
if (!Mesh.__gl_meshSplice(e, e.Sym)) return false;
} else {
/* Create a new vertex and edge which immediately follow e
* in the ordering around the left face.
*/
/* Create a new vertex and edge which immediately follow e
* in the ordering around the left face.
*/
if (Mesh.__gl_meshSplitEdge(e) == null) return false;
e = e.Lnext;
}
/* The new vertex is now e.Org. */
/* The new vertex is now e.Org. */
e.Org.data = vertexData;
e.Org.coords[0] = coords[0];
e.Org.coords[1] = coords[1];
e.Org.coords[2] = coords[2];
/* The winding of an edge says how the winding number changes as we
* cross from the edge''s right face to its left face. We add the
* vertices in such an order that a CCW contour will add +1 to
* the winding number of the region inside the contour.
*/
/* The winding of an edge says how the winding number changes as we
* cross from the edge''s right face to its left face. We add the
* vertices in such an order that a CCW contour will add +1 to
* the winding number of the region inside the contour.
*/
e.winding = 1;
e.Sym.winding = -1;
@@ -414,7 +410,6 @@ public class GLUtessellatorImpl implements GLUtessellator {
++cacheCount;
}
private boolean flushCache() {
CachedVertex[] v = cache;
@@ -447,7 +442,7 @@ public class GLUtessellatorImpl implements GLUtessellator {
lastEdge = null;
}
for (i = 0; i < 3; ++i) {
x = coords[i+coords_offset];
x = coords[i + coords_offset];
if (x < -GLU_TESS_MAX_COORD) {
x = -GLU_TESS_MAX_COORD;
tooLarge = true;
@@ -478,7 +473,6 @@ public class GLUtessellatorImpl implements GLUtessellator {
}
}
public void gluTessBeginPolygon(Object data) {
requireState(TessState.T_DORMANT);
@@ -490,22 +484,20 @@ public class GLUtessellatorImpl implements GLUtessellator {
polygonData = data;
}
public void gluTessBeginContour() {
requireState(TessState.T_IN_POLYGON);
state = TessState.T_IN_CONTOUR;
lastEdge = null;
if (cacheCount > 0) {
/* Just set a flag so we don't get confused by empty contours
* -- these can be generated accidentally with the obsolete
* NextContour() interface.
*/
/* Just set a flag so we don't get confused by empty contours
* -- these can be generated accidentally with the obsolete
* NextContour() interface.
*/
flushCacheOnNextVertex = true;
}
}
public void gluTessEndContour() {
requireState(TessState.T_IN_CONTOUR);
state = TessState.T_IN_POLYGON;
@@ -521,11 +513,11 @@ public class GLUtessellatorImpl implements GLUtessellator {
if (this.mesh == null) {
if (!flagBoundary /*&& callMesh == NULL_CB*/) {
/* Try some special code to make the easy cases go quickly
* (eg. convex polygons). This code does NOT handle multiple contours,
* intersections, edge flags, and of course it does not generate
* an explicit mesh either.
*/
/* Try some special code to make the easy cases go quickly
* (eg. convex polygons). This code does NOT handle multiple contours,
* intersections, edge flags, and of course it does not generate
* an explicit mesh either.
*/
if (Render.__gl_renderCache(this)) {
polygonData = null;
return;
@@ -534,64 +526,66 @@ public class GLUtessellatorImpl implements GLUtessellator {
if (!flushCache()) throw new RuntimeException(); /* could've used a label*/
}
/* Determine the polygon normal and project vertices onto the plane
* of the polygon.
*/
/* Determine the polygon normal and project vertices onto the plane
* of the polygon.
*/
Normal.__gl_projectPolygon(this);
/* __gl_computeInterior( tess ) computes the planar arrangement specified
* by the given contours, and further subdivides this arrangement
* into regions. Each region is marked "inside" if it belongs
* to the polygon, according to the rule given by windingRule.
* Each interior region is guaranteed be monotone.
*/
/* __gl_computeInterior( tess ) computes the planar arrangement specified
* by the given contours, and further subdivides this arrangement
* into regions. Each region is marked "inside" if it belongs
* to the polygon, according to the rule given by windingRule.
* Each interior region is guaranteed be monotone.
*/
if (!Sweep.__gl_computeInterior(this)) {
throw new RuntimeException(); /* could've used a label */
throw new RuntimeException(); /* could've used a label */
}
mesh = this.mesh;
if (!fatalError) {
boolean rc = true;
/* If the user wants only the boundary contours, we throw away all edges
* except those which separate the interior from the exterior.
* Otherwise we tessellate all the regions marked "inside".
*/
/* If the user wants only the boundary contours, we throw away all edges
* except those which separate the interior from the exterior.
* Otherwise we tessellate all the regions marked "inside".
*/
if (boundaryOnly) {
rc = TessMono.__gl_meshSetWindingNumber(mesh, 1, true);
} else {
rc = TessMono.__gl_meshTessellateInterior(mesh);
}
if (!rc) throw new RuntimeException(); /* could've used a label */
if (!rc) throw new RuntimeException(); /* could've used a label */
Mesh.__gl_meshCheckMesh(mesh);
if (callBegin != NULL_CB || callEnd != NULL_CB
|| callVertex != NULL_CB || callEdgeFlag != NULL_CB
if (callBegin != NULL_CB
|| callEnd != NULL_CB
|| callVertex != NULL_CB
|| callEdgeFlag != NULL_CB
|| callBeginData != NULL_CB
|| callEndData != NULL_CB
|| callVertexData != NULL_CB
|| callEdgeFlagData != NULL_CB) {
if (boundaryOnly) {
Render.__gl_renderBoundary(this, mesh); /* output boundary contours */
Render.__gl_renderBoundary(this, mesh); /* output boundary contours */
} else {
Render.__gl_renderMesh(this, mesh); /* output strips and fans */
Render.__gl_renderMesh(this, mesh); /* output strips and fans */
}
}
// if (callMesh != NULL_CB) {
//
///* Throw away the exterior faces, so that all faces are interior.
// * This way the user doesn't have to check the "inside" flag,
// * and we don't need to even reveal its existence. It also leaves
// * the freedom for an implementation to not generate the exterior
// * faces in the first place.
// */
// TessMono.__gl_meshDiscardExterior(mesh);
// callMesh.mesh(mesh); /* user wants the mesh itself */
// mesh = null;
// polygonData = null;
// return;
// }
// if (callMesh != NULL_CB) {
//
/// * Throw away the exterior faces, so that all faces are interior.
// * This way the user doesn't have to check the "inside" flag,
// * and we don't need to even reveal its existence. It also leaves
// * the freedom for an implementation to not generate the exterior
// * faces in the first place.
// */
// TessMono.__gl_meshDiscardExterior(mesh);
// callMesh.mesh(mesh); /* user wants the mesh itself */
// mesh = null;
// polygonData = null;
// return;
// }
}
Mesh.__gl_meshDeleteMesh(mesh);
polygonData = null;
@@ -604,66 +598,51 @@ public class GLUtessellatorImpl implements GLUtessellator {
/*******************************************************/
/* Obsolete calls -- for backward compatibility */
/* Obsolete calls -- for backward compatibility */
public void gluBeginPolygon() {
gluTessBeginPolygon(null);
gluTessBeginContour();
}
/*ARGSUSED*/
/*ARGSUSED*/
public void gluNextContour(int type) {
gluTessEndContour();
gluTessBeginContour();
}
public void gluEndPolygon() {
gluTessEndContour();
gluTessEndPolygon();
}
void callBeginOrBeginData(int a) {
if (callBeginData != NULL_CB)
callBeginData.beginData(a, polygonData);
else
callBegin.begin(a);
if (callBeginData != NULL_CB) callBeginData.beginData(a, polygonData);
else callBegin.begin(a);
}
void callVertexOrVertexData(Object a) {
if (callVertexData != NULL_CB)
callVertexData.vertexData(a, polygonData);
else
callVertex.vertex(a);
if (callVertexData != NULL_CB) callVertexData.vertexData(a, polygonData);
else callVertex.vertex(a);
}
void callEdgeFlagOrEdgeFlagData(boolean a) {
if (callEdgeFlagData != NULL_CB)
callEdgeFlagData.edgeFlagData(a, polygonData);
else
callEdgeFlag.edgeFlag(a);
if (callEdgeFlagData != NULL_CB) callEdgeFlagData.edgeFlagData(a, polygonData);
else callEdgeFlag.edgeFlag(a);
}
void callEndOrEndData() {
if (callEndData != NULL_CB)
callEndData.endData(polygonData);
else
callEnd.end();
if (callEndData != NULL_CB) callEndData.endData(polygonData);
else callEnd.end();
}
void callCombineOrCombineData(double[] coords, Object[] vertexData, float[] weights, Object[] outData) {
if (callCombineData != NULL_CB)
callCombineData.combineData(coords, vertexData, weights, outData, polygonData);
else
callCombine.combine(coords, vertexData, weights, outData);
if (callCombineData != NULL_CB) callCombineData.combineData(coords, vertexData, weights, outData, polygonData);
else callCombine.combine(coords, vertexData, weights, outData);
}
void callErrorOrErrorData(int a) {
if (callErrorData != NULL_CB)
callErrorData.errorData(a, polygonData);
else
callError.error(a);
if (callErrorData != NULL_CB) callErrorData.errorData(a, polygonData);
else callError.error(a);
}
}
@@ -31,67 +31,67 @@
*/
/*
* Portions Copyright (C) 2003-2006 Sun Microsystems, Inc.
* All rights reserved.
*/
* Portions Copyright (C) 2003-2006 Sun Microsystems, Inc.
* All rights reserved.
*/
/*
** License Applicability. Except to the extent portions of this file are
** made subject to an alternative license as permitted in the SGI Free
** Software License B, Version 1.1 (the "License"), the contents of this
** file are subject only to the provisions of the License. You may not use
** this file except in compliance with the License. You may obtain a copy
** of the License at Silicon Graphics, Inc., attn: Legal Services, 1600
** Amphitheatre Parkway, Mountain View, CA 94043-1351, or at:
**
** http://oss.sgi.com/projects/FreeB
**
** Note that, as provided in the License, the Software is distributed on an
** "AS IS" basis, with ALL EXPRESS AND IMPLIED WARRANTIES AND CONDITIONS
** DISCLAIMED, INCLUDING, WITHOUT LIMITATION, ANY IMPLIED WARRANTIES AND
** CONDITIONS OF MERCHANTABILITY, SATISFACTORY QUALITY, FITNESS FOR A
** PARTICULAR PURPOSE, AND NON-INFRINGEMENT.
**
** NOTE: The Original Code (as defined below) has been licensed to Sun
** Microsystems, Inc. ("Sun") under the SGI Free Software License B
** (Version 1.1), shown above ("SGI License"). Pursuant to Section
** 3.2(3) of the SGI License, Sun is distributing the Covered Code to
** you under an alternative license ("Alternative License"). This
** Alternative License includes all of the provisions of the SGI License
** except that Section 2.2 and 11 are omitted. Any differences between
** the Alternative License and the SGI License are offered solely by Sun
** and not by SGI.
**
** Original Code. The Original Code is: OpenGL Sample Implementation,
** Version 1.2.1, released January 26, 2000, developed by Silicon Graphics,
** Inc. The Original Code is Copyright (c) 1991-2000 Silicon Graphics, Inc.
** Copyright in any portions created by third parties is as indicated
** elsewhere herein. All Rights Reserved.
**
** Additional Notice Provisions: The application programming interfaces
** established by SGI in conjunction with the Original Code are The
** OpenGL(R) Graphics System: A Specification (Version 1.2.1), released
** April 1, 1999; The OpenGL(R) Graphics System Utility Library (Version
** 1.3), released November 4, 1998; and OpenGL(R) Graphics with the X
** Window System(R) (Version 1.3), released October 19, 1998. This software
** was created using the OpenGL(R) version 1.2.1 Sample Implementation
** published by SGI, but has not been independently verified as being
** compliant with the OpenGL(R) version 1.2.1 Specification.
**
** Author: Eric Veach, July 1994
** Java Port: Pepijn Van Eeckhoudt, July 2003
** Java Port: Nathan Parker Burg, August 2003
*/
** License Applicability. Except to the extent portions of this file are
** made subject to an alternative license as permitted in the SGI Free
** Software License B, Version 1.1 (the "License"), the contents of this
** file are subject only to the provisions of the License. You may not use
** this file except in compliance with the License. You may obtain a copy
** of the License at Silicon Graphics, Inc., attn: Legal Services, 1600
** Amphitheatre Parkway, Mountain View, CA 94043-1351, or at:
**
** http://oss.sgi.com/projects/FreeB
**
** Note that, as provided in the License, the Software is distributed on an
** "AS IS" basis, with ALL EXPRESS AND IMPLIED WARRANTIES AND CONDITIONS
** DISCLAIMED, INCLUDING, WITHOUT LIMITATION, ANY IMPLIED WARRANTIES AND
** CONDITIONS OF MERCHANTABILITY, SATISFACTORY QUALITY, FITNESS FOR A
** PARTICULAR PURPOSE, AND NON-INFRINGEMENT.
**
** NOTE: The Original Code (as defined below) has been licensed to Sun
** Microsystems, Inc. ("Sun") under the SGI Free Software License B
** (Version 1.1), shown above ("SGI License"). Pursuant to Section
** 3.2(3) of the SGI License, Sun is distributing the Covered Code to
** you under an alternative license ("Alternative License"). This
** Alternative License includes all of the provisions of the SGI License
** except that Section 2.2 and 11 are omitted. Any differences between
** the Alternative License and the SGI License are offered solely by Sun
** and not by SGI.
**
** Original Code. The Original Code is: OpenGL Sample Implementation,
** Version 1.2.1, released January 26, 2000, developed by Silicon Graphics,
** Inc. The Original Code is Copyright (c) 1991-2000 Silicon Graphics, Inc.
** Copyright in any portions created by third parties is as indicated
** elsewhere herein. All Rights Reserved.
**
** Additional Notice Provisions: The application programming interfaces
** established by SGI in conjunction with the Original Code are The
** OpenGL(R) Graphics System: A Specification (Version 1.2.1), released
** April 1, 1999; The OpenGL(R) Graphics System Utility Library (Version
** 1.3), released November 4, 1998; and OpenGL(R) Graphics with the X
** Window System(R) (Version 1.3), released October 19, 1998. This software
** was created using the OpenGL(R) version 1.2.1 Sample Implementation
** published by SGI, but has not been independently verified as being
** compliant with the OpenGL(R) version 1.2.1 Specification.
**
** Author: Eric Veach, July 1994
** Java Port: Pepijn Van Eeckhoudt, July 2003
** Java Port: Nathan Parker Burg, August 2003
*/
package org.lwjglx.util.glu.tessellation;
class GLUvertex {
public GLUvertex next; /* next vertex (never NULL) */
public GLUvertex prev; /* previous vertex (never NULL) */
public GLUhalfEdge anEdge; /* a half-edge with this origin */
public Object data; /* client's data */
public GLUvertex next; /* next vertex (never NULL) */
public GLUvertex prev; /* previous vertex (never NULL) */
public GLUhalfEdge anEdge; /* a half-edge with this origin */
public Object data; /* client's data */
/* Internal data (keep hidden) */
public double[] coords = new double[3]; /* vertex location in 3D */
public double s, t; /* projection onto the sweep plane */
public int pqHandle; /* to allow deletion from priority queue */
public double[] coords = new double[3]; /* vertex location in 3D */
public double s, t; /* projection onto the sweep plane */
public int pqHandle; /* to allow deletion from priority queue */
}
@@ -31,62 +31,61 @@
*/
/*
* Portions Copyright (C) 2003-2006 Sun Microsystems, Inc.
* All rights reserved.
*/
* Portions Copyright (C) 2003-2006 Sun Microsystems, Inc.
* All rights reserved.
*/
/*
** License Applicability. Except to the extent portions of this file are
** made subject to an alternative license as permitted in the SGI Free
** Software License B, Version 1.1 (the "License"), the contents of this
** file are subject only to the provisions of the License. You may not use
** this file except in compliance with the License. You may obtain a copy
** of the License at Silicon Graphics, Inc., attn: Legal Services, 1600
** Amphitheatre Parkway, Mountain View, CA 94043-1351, or at:
**
** http://oss.sgi.com/projects/FreeB
**
** Note that, as provided in the License, the Software is distributed on an
** "AS IS" basis, with ALL EXPRESS AND IMPLIED WARRANTIES AND CONDITIONS
** DISCLAIMED, INCLUDING, WITHOUT LIMITATION, ANY IMPLIED WARRANTIES AND
** CONDITIONS OF MERCHANTABILITY, SATISFACTORY QUALITY, FITNESS FOR A
** PARTICULAR PURPOSE, AND NON-INFRINGEMENT.
**
** NOTE: The Original Code (as defined below) has been licensed to Sun
** Microsystems, Inc. ("Sun") under the SGI Free Software License B
** (Version 1.1), shown above ("SGI License"). Pursuant to Section
** 3.2(3) of the SGI License, Sun is distributing the Covered Code to
** you under an alternative license ("Alternative License"). This
** Alternative License includes all of the provisions of the SGI License
** except that Section 2.2 and 11 are omitted. Any differences between
** the Alternative License and the SGI License are offered solely by Sun
** and not by SGI.
**
** Original Code. The Original Code is: OpenGL Sample Implementation,
** Version 1.2.1, released January 26, 2000, developed by Silicon Graphics,
** Inc. The Original Code is Copyright (c) 1991-2000 Silicon Graphics, Inc.
** Copyright in any portions created by third parties is as indicated
** elsewhere herein. All Rights Reserved.
**
** Additional Notice Provisions: The application programming interfaces
** established by SGI in conjunction with the Original Code are The
** OpenGL(R) Graphics System: A Specification (Version 1.2.1), released
** April 1, 1999; The OpenGL(R) Graphics System Utility Library (Version
** 1.3), released November 4, 1998; and OpenGL(R) Graphics with the X
** Window System(R) (Version 1.3), released October 19, 1998. This software
** was created using the OpenGL(R) version 1.2.1 Sample Implementation
** published by SGI, but has not been independently verified as being
** compliant with the OpenGL(R) version 1.2.1 Specification.
**
** Author: Eric Veach, July 1994
** Java Port: Pepijn Van Eeckhoudt, July 2003
** Java Port: Nathan Parker Burg, August 2003
*/
** License Applicability. Except to the extent portions of this file are
** made subject to an alternative license as permitted in the SGI Free
** Software License B, Version 1.1 (the "License"), the contents of this
** file are subject only to the provisions of the License. You may not use
** this file except in compliance with the License. You may obtain a copy
** of the License at Silicon Graphics, Inc., attn: Legal Services, 1600
** Amphitheatre Parkway, Mountain View, CA 94043-1351, or at:
**
** http://oss.sgi.com/projects/FreeB
**
** Note that, as provided in the License, the Software is distributed on an
** "AS IS" basis, with ALL EXPRESS AND IMPLIED WARRANTIES AND CONDITIONS
** DISCLAIMED, INCLUDING, WITHOUT LIMITATION, ANY IMPLIED WARRANTIES AND
** CONDITIONS OF MERCHANTABILITY, SATISFACTORY QUALITY, FITNESS FOR A
** PARTICULAR PURPOSE, AND NON-INFRINGEMENT.
**
** NOTE: The Original Code (as defined below) has been licensed to Sun
** Microsystems, Inc. ("Sun") under the SGI Free Software License B
** (Version 1.1), shown above ("SGI License"). Pursuant to Section
** 3.2(3) of the SGI License, Sun is distributing the Covered Code to
** you under an alternative license ("Alternative License"). This
** Alternative License includes all of the provisions of the SGI License
** except that Section 2.2 and 11 are omitted. Any differences between
** the Alternative License and the SGI License are offered solely by Sun
** and not by SGI.
**
** Original Code. The Original Code is: OpenGL Sample Implementation,
** Version 1.2.1, released January 26, 2000, developed by Silicon Graphics,
** Inc. The Original Code is Copyright (c) 1991-2000 Silicon Graphics, Inc.
** Copyright in any portions created by third parties is as indicated
** elsewhere herein. All Rights Reserved.
**
** Additional Notice Provisions: The application programming interfaces
** established by SGI in conjunction with the Original Code are The
** OpenGL(R) Graphics System: A Specification (Version 1.2.1), released
** April 1, 1999; The OpenGL(R) Graphics System Utility Library (Version
** 1.3), released November 4, 1998; and OpenGL(R) Graphics with the X
** Window System(R) (Version 1.3), released October 19, 1998. This software
** was created using the OpenGL(R) version 1.2.1 Sample Implementation
** published by SGI, but has not been independently verified as being
** compliant with the OpenGL(R) version 1.2.1 Specification.
**
** Author: Eric Veach, July 1994
** Java Port: Pepijn Van Eeckhoudt, July 2003
** Java Port: Nathan Parker Burg, August 2003
*/
package org.lwjglx.util.glu.tessellation;
class Geom {
private Geom() {
}
private Geom() {}
/* Given three vertices u,v,w such that VertLeq(u,v) && VertLeq(v,w),
* evaluates the t-coord of the edge uw at the s-coord of the vertex v.
@@ -132,11 +131,9 @@ class Geom {
return 0;
}
/***********************************************************************
* Define versions of EdgeSign, EdgeEval with s and t transposed.
*/
static double TransEval(GLUvertex u, GLUvertex v, GLUvertex w) {
/* Given three vertices u,v,w such that TransLeq(u,v) && TransLeq(v,w),
* evaluates the t-coord of the edge uw at the s-coord of the vertex v.
@@ -185,7 +182,6 @@ class Geom {
return 0;
}
static boolean VertCCW(GLUvertex u, GLUvertex v, GLUvertex w) {
/* For almost-degenerate situations, the results are not reliable.
* Unless the floating-point arithmetic can be performed without
@@ -196,14 +192,14 @@ class Geom {
return (u.s * (v.t - w.t) + v.s * (w.t - u.t) + w.s * (u.t - v.t)) >= 0;
}
/* Given parameters a,x,b,y returns the value (b*x+a*y)/(a+b),
* or (x+y)/2 if a==b==0. It requires that a,b >= 0, and enforces
* this in the rare case that one argument is slightly negative.
* The implementation is extremely stable numerically.
* In particular it guarantees that the result r satisfies
* MIN(x,y) <= r <= MAX(x,y), and the results are very accurate
* even when a and b differ greatly in magnitude.
*/
/* Given parameters a,x,b,y returns the value (b*x+a*y)/(a+b),
* or (x+y)/2 if a==b==0. It requires that a,b >= 0, and enforces
* this in the rare case that one argument is slightly negative.
* The implementation is extremely stable numerically.
* In particular it guarantees that the result r satisfies
* MIN(x,y) <= r <= MAX(x,y), and the results are very accurate
* even when a and b differ greatly in magnitude.
*/
static double Interpolate(double a, double x, double b, double y) {
a = (a < 0) ? 0 : a;
b = (b < 0) ? 0 : b;
@@ -218,13 +214,11 @@ class Geom {
}
}
static void EdgeIntersect(GLUvertex o1, GLUvertex d1,
GLUvertex o2, GLUvertex d2,
GLUvertex v)
/* Given edges (o1,d1) and (o2,d2), compute their point of intersection.
* The computed point is guaranteed to lie in the intersection of the
* bounding rectangles defined by each edge.
*/ {
static void EdgeIntersect(GLUvertex o1, GLUvertex d1, GLUvertex o2, GLUvertex d2, GLUvertex v)
/* Given edges (o1,d1) and (o2,d2), compute their point of intersection.
* The computed point is guaranteed to lie in the intersection of the
* bounding rectangles defined by each edge.
*/ {
double z1, z2;
/* This is certainly not the most efficient way to find the intersection
@@ -330,7 +324,7 @@ class Geom {
return u.s < v.s || (u.s == v.s && u.t <= v.t);
}
/* Versions of VertLeq, EdgeSign, EdgeEval with s and t transposed. */
/* Versions of VertLeq, EdgeSign, EdgeEval with s and t transposed. */
static boolean TransLeq(GLUvertex u, GLUvertex v) {
return u.t < v.t || (u.t == v.t && u.s <= v.s);
@@ -31,83 +31,81 @@
*/
/*
* Portions Copyright (C) 2003-2006 Sun Microsystems, Inc.
* All rights reserved.
*/
* Portions Copyright (C) 2003-2006 Sun Microsystems, Inc.
* All rights reserved.
*/
/*
** License Applicability. Except to the extent portions of this file are
** made subject to an alternative license as permitted in the SGI Free
** Software License B, Version 1.1 (the "License"), the contents of this
** file are subject only to the provisions of the License. You may not use
** this file except in compliance with the License. You may obtain a copy
** of the License at Silicon Graphics, Inc., attn: Legal Services, 1600
** Amphitheatre Parkway, Mountain View, CA 94043-1351, or at:
**
** http://oss.sgi.com/projects/FreeB
**
** Note that, as provided in the License, the Software is distributed on an
** "AS IS" basis, with ALL EXPRESS AND IMPLIED WARRANTIES AND CONDITIONS
** DISCLAIMED, INCLUDING, WITHOUT LIMITATION, ANY IMPLIED WARRANTIES AND
** CONDITIONS OF MERCHANTABILITY, SATISFACTORY QUALITY, FITNESS FOR A
** PARTICULAR PURPOSE, AND NON-INFRINGEMENT.
**
** NOTE: The Original Code (as defined below) has been licensed to Sun
** Microsystems, Inc. ("Sun") under the SGI Free Software License B
** (Version 1.1), shown above ("SGI License"). Pursuant to Section
** 3.2(3) of the SGI License, Sun is distributing the Covered Code to
** you under an alternative license ("Alternative License"). This
** Alternative License includes all of the provisions of the SGI License
** except that Section 2.2 and 11 are omitted. Any differences between
** the Alternative License and the SGI License are offered solely by Sun
** and not by SGI.
**
** Original Code. The Original Code is: OpenGL Sample Implementation,
** Version 1.2.1, released January 26, 2000, developed by Silicon Graphics,
** Inc. The Original Code is Copyright (c) 1991-2000 Silicon Graphics, Inc.
** Copyright in any portions created by third parties is as indicated
** elsewhere herein. All Rights Reserved.
**
** Additional Notice Provisions: The application programming interfaces
** established by SGI in conjunction with the Original Code are The
** OpenGL(R) Graphics System: A Specification (Version 1.2.1), released
** April 1, 1999; The OpenGL(R) Graphics System Utility Library (Version
** 1.3), released November 4, 1998; and OpenGL(R) Graphics with the X
** Window System(R) (Version 1.3), released October 19, 1998. This software
** was created using the OpenGL(R) version 1.2.1 Sample Implementation
** published by SGI, but has not been independently verified as being
** compliant with the OpenGL(R) version 1.2.1 Specification.
**
** Author: Eric Veach, July 1994
** Java Port: Pepijn Van Eeckhoudt, July 2003
** Java Port: Nathan Parker Burg, August 2003
*/
** License Applicability. Except to the extent portions of this file are
** made subject to an alternative license as permitted in the SGI Free
** Software License B, Version 1.1 (the "License"), the contents of this
** file are subject only to the provisions of the License. You may not use
** this file except in compliance with the License. You may obtain a copy
** of the License at Silicon Graphics, Inc., attn: Legal Services, 1600
** Amphitheatre Parkway, Mountain View, CA 94043-1351, or at:
**
** http://oss.sgi.com/projects/FreeB
**
** Note that, as provided in the License, the Software is distributed on an
** "AS IS" basis, with ALL EXPRESS AND IMPLIED WARRANTIES AND CONDITIONS
** DISCLAIMED, INCLUDING, WITHOUT LIMITATION, ANY IMPLIED WARRANTIES AND
** CONDITIONS OF MERCHANTABILITY, SATISFACTORY QUALITY, FITNESS FOR A
** PARTICULAR PURPOSE, AND NON-INFRINGEMENT.
**
** NOTE: The Original Code (as defined below) has been licensed to Sun
** Microsystems, Inc. ("Sun") under the SGI Free Software License B
** (Version 1.1), shown above ("SGI License"). Pursuant to Section
** 3.2(3) of the SGI License, Sun is distributing the Covered Code to
** you under an alternative license ("Alternative License"). This
** Alternative License includes all of the provisions of the SGI License
** except that Section 2.2 and 11 are omitted. Any differences between
** the Alternative License and the SGI License are offered solely by Sun
** and not by SGI.
**
** Original Code. The Original Code is: OpenGL Sample Implementation,
** Version 1.2.1, released January 26, 2000, developed by Silicon Graphics,
** Inc. The Original Code is Copyright (c) 1991-2000 Silicon Graphics, Inc.
** Copyright in any portions created by third parties is as indicated
** elsewhere herein. All Rights Reserved.
**
** Additional Notice Provisions: The application programming interfaces
** established by SGI in conjunction with the Original Code are The
** OpenGL(R) Graphics System: A Specification (Version 1.2.1), released
** April 1, 1999; The OpenGL(R) Graphics System Utility Library (Version
** 1.3), released November 4, 1998; and OpenGL(R) Graphics with the X
** Window System(R) (Version 1.3), released October 19, 1998. This software
** was created using the OpenGL(R) version 1.2.1 Sample Implementation
** published by SGI, but has not been independently verified as being
** compliant with the OpenGL(R) version 1.2.1 Specification.
**
** Author: Eric Veach, July 1994
** Java Port: Pepijn Van Eeckhoudt, July 2003
** Java Port: Nathan Parker Burg, August 2003
*/
package org.lwjglx.util.glu.tessellation;
class Mesh {
private Mesh() {
}
private Mesh() {}
/************************ Utility Routines ************************/
/* MakeEdge creates a new pair of half-edges which form their own loop.
* No vertex or face structures are allocated, but these must be assigned
* before the current edge operation is completed.
*/
/* MakeEdge creates a new pair of half-edges which form their own loop.
* No vertex or face structures are allocated, but these must be assigned
* before the current edge operation is completed.
*/
static GLUhalfEdge MakeEdge(GLUhalfEdge eNext) {
GLUhalfEdge e;
GLUhalfEdge eSym;
GLUhalfEdge ePrev;
// EdgePair * pair = (EdgePair *)
// memAlloc(sizeof(EdgePair));
// if (pair == NULL) return NULL;
//
// e = &pair - > e;
// EdgePair * pair = (EdgePair *)
// memAlloc(sizeof(EdgePair));
// if (pair == NULL) return NULL;
//
// e = &pair - > e;
e = new GLUhalfEdge(true);
// eSym = &pair - > eSym;
// eSym = &pair - > eSym;
eSym = new GLUhalfEdge(false);
/* Make sure eNext points to the first edge of the edge pair */
if (!eNext.first) {
eNext = eNext.Sym;
@@ -141,12 +139,12 @@ class Mesh {
return e;
}
/* Splice( a, b ) is best described by the Guibas/Stolfi paper or the
* CS348a notes (see mesh.h). Basically it modifies the mesh so that
* a->Onext and b->Onext are exchanged. This can have various effects
* depending on whether a and b belong to different face or vertex rings.
* For more explanation see __gl_meshSplice() below.
*/
/* Splice( a, b ) is best described by the Guibas/Stolfi paper or the
* CS348a notes (see mesh.h). Basically it modifies the mesh so that
* a->Onext and b->Onext are exchanged. This can have various effects
* depending on whether a and b belong to different face or vertex rings.
* For more explanation see __gl_meshSplice() below.
*/
static void Splice(GLUhalfEdge a, GLUhalfEdge b) {
GLUhalfEdge aOnext = a.Onext;
GLUhalfEdge bOnext = b.Onext;
@@ -157,14 +155,13 @@ class Mesh {
b.Onext = aOnext;
}
/* MakeVertex( newVertex, eOrig, vNext ) attaches a new vertex and makes it the
* origin of all edges in the vertex loop to which eOrig belongs. "vNext" gives
* a place to insert the new vertex in the global vertex list. We insert
* the new vertex *before* vNext so that algorithms which walk the vertex
* list will not see the newly created vertices.
*/
static void MakeVertex(GLUvertex newVertex,
GLUhalfEdge eOrig, GLUvertex vNext) {
/* MakeVertex( newVertex, eOrig, vNext ) attaches a new vertex and makes it the
* origin of all edges in the vertex loop to which eOrig belongs. "vNext" gives
* a place to insert the new vertex in the global vertex list. We insert
* the new vertex *before* vNext so that algorithms which walk the vertex
* list will not see the newly created vertices.
*/
static void MakeVertex(GLUvertex newVertex, GLUhalfEdge eOrig, GLUvertex vNext) {
GLUhalfEdge e;
GLUvertex vPrev;
GLUvertex vNew = newVertex;
@@ -190,12 +187,12 @@ class Mesh {
} while (e != eOrig);
}
/* MakeFace( newFace, eOrig, fNext ) attaches a new face and makes it the left
* face of all edges in the face loop to which eOrig belongs. "fNext" gives
* a place to insert the new face in the global face list. We insert
* the new face *before* fNext so that algorithms which walk the face
* list will not see the newly created faces.
*/
/* MakeFace( newFace, eOrig, fNext ) attaches a new face and makes it the left
* face of all edges in the face loop to which eOrig belongs. "fNext" gives
* a place to insert the new face in the global face list. We insert
* the new face *before* fNext so that algorithms which walk the face
* list will not see the newly created faces.
*/
static void MakeFace(GLUface newFace, GLUhalfEdge eOrig, GLUface fNext) {
GLUhalfEdge e;
GLUface fPrev;
@@ -228,9 +225,9 @@ class Mesh {
} while (e != eOrig);
}
/* KillEdge( eDel ) destroys an edge (the half-edges eDel and eDel->Sym),
* and removes from the global edge list.
*/
/* KillEdge( eDel ) destroys an edge (the half-edges eDel and eDel->Sym),
* and removes from the global edge list.
*/
static void KillEdge(GLUhalfEdge eDel) {
GLUhalfEdge ePrev, eNext;
@@ -246,10 +243,9 @@ class Mesh {
ePrev.Sym.next = eNext;
}
/* KillVertex( vDel ) destroys a vertex and removes it from the global
* vertex list. It updates the vertex loop to point to a given new vertex.
*/
/* KillVertex( vDel ) destroys a vertex and removes it from the global
* vertex list. It updates the vertex loop to point to a given new vertex.
*/
static void KillVertex(GLUvertex vDel, GLUvertex newOrg) {
GLUhalfEdge e, eStart = vDel.anEdge;
GLUvertex vPrev, vNext;
@@ -268,9 +264,9 @@ class Mesh {
vPrev.next = vNext;
}
/* KillFace( fDel ) destroys a face and removes it from the global face
* list. It updates the face loop to point to a given new face.
*/
/* KillFace( fDel ) destroys a face and removes it from the global face
* list. It updates the face loop to point to a given new face.
*/
static void KillFace(GLUface fDel, GLUface newLface) {
GLUhalfEdge e, eStart = fDel.anEdge;
GLUface fPrev, fNext;
@@ -289,12 +285,11 @@ class Mesh {
fPrev.next = fNext;
}
/****************** Basic Edge Operations **********************/
/* __gl_meshMakeEdge creates one edge, two vertices, and a loop (face).
* The loop consists of the two new half-edges.
*/
/* __gl_meshMakeEdge creates one edge, two vertices, and a loop (face).
* The loop consists of the two new half-edges.
*/
public static GLUhalfEdge __gl_meshMakeEdge(GLUmesh mesh) {
GLUvertex newVertex1 = new GLUvertex();
GLUvertex newVertex2 = new GLUvertex();
@@ -310,30 +305,29 @@ class Mesh {
return e;
}
/* __gl_meshSplice( eOrg, eDst ) is the basic operation for changing the
* mesh connectivity and topology. It changes the mesh so that
* eOrg->Onext <- OLD( eDst->Onext )
* eDst->Onext <- OLD( eOrg->Onext )
* where OLD(...) means the value before the meshSplice operation.
*
* This can have two effects on the vertex structure:
* - if eOrg->Org != eDst->Org, the two vertices are merged together
* - if eOrg->Org == eDst->Org, the origin is split into two vertices
* In both cases, eDst->Org is changed and eOrg->Org is untouched.
*
* Similarly (and independently) for the face structure,
* - if eOrg->Lface == eDst->Lface, one loop is split into two
* - if eOrg->Lface != eDst->Lface, two distinct loops are joined into one
* In both cases, eDst->Lface is changed and eOrg->Lface is unaffected.
*
* Some special cases:
* If eDst == eOrg, the operation has no effect.
* If eDst == eOrg->Lnext, the new face will have a single edge.
* If eDst == eOrg->Lprev, the old face will have a single edge.
* If eDst == eOrg->Onext, the new vertex will have a single edge.
* If eDst == eOrg->Oprev, the old vertex will have a single edge.
*/
/* __gl_meshSplice( eOrg, eDst ) is the basic operation for changing the
* mesh connectivity and topology. It changes the mesh so that
* eOrg->Onext <- OLD( eDst->Onext )
* eDst->Onext <- OLD( eOrg->Onext )
* where OLD(...) means the value before the meshSplice operation.
*
* This can have two effects on the vertex structure:
* - if eOrg->Org != eDst->Org, the two vertices are merged together
* - if eOrg->Org == eDst->Org, the origin is split into two vertices
* In both cases, eDst->Org is changed and eOrg->Org is untouched.
*
* Similarly (and independently) for the face structure,
* - if eOrg->Lface == eDst->Lface, one loop is split into two
* - if eOrg->Lface != eDst->Lface, two distinct loops are joined into one
* In both cases, eDst->Lface is changed and eOrg->Lface is unaffected.
*
* Some special cases:
* If eDst == eOrg, the operation has no effect.
* If eDst == eOrg->Lnext, the new face will have a single edge.
* If eDst == eOrg->Lprev, the old face will have a single edge.
* If eDst == eOrg->Onext, the new vertex will have a single edge.
* If eDst == eOrg->Oprev, the old vertex will have a single edge.
*/
public static boolean __gl_meshSplice(GLUhalfEdge eOrg, GLUhalfEdge eDst) {
boolean joiningLoops = false;
boolean joiningVertices = false;
@@ -376,17 +370,16 @@ class Mesh {
return true;
}
/* __gl_meshDelete( eDel ) removes the edge eDel. There are several cases:
* if (eDel.Lface != eDel.Rface), we join two loops into one; the loop
* eDel.Lface is deleted. Otherwise, we are splitting one loop into two;
* the newly created loop will contain eDel.Dst. If the deletion of eDel
* would create isolated vertices, those are deleted as well.
*
* This function could be implemented as two calls to __gl_meshSplice
* plus a few calls to memFree, but this would allocate and delete
* unnecessary vertices and faces.
*/
/* __gl_meshDelete( eDel ) removes the edge eDel. There are several cases:
* if (eDel.Lface != eDel.Rface), we join two loops into one; the loop
* eDel.Lface is deleted. Otherwise, we are splitting one loop into two;
* the newly created loop will contain eDel.Dst. If the deletion of eDel
* would create isolated vertices, those are deleted as well.
*
* This function could be implemented as two calls to __gl_meshSplice
* plus a few calls to memFree, but this would allocate and delete
* unnecessary vertices and faces.
*/
static boolean __gl_meshDelete(GLUhalfEdge eDel) {
GLUhalfEdge eDelSym = eDel.Sym;
boolean joiningLoops = false;
@@ -435,18 +428,16 @@ class Mesh {
return true;
}
/******************** Other Edge Operations **********************/
/* All these routines can be implemented with the basic edge
* operations above. They are provided for convenience and efficiency.
*/
/* All these routines can be implemented with the basic edge
* operations above. They are provided for convenience and efficiency.
*/
/* __gl_meshAddEdgeVertex( eOrg ) creates a new edge eNew such that
* eNew == eOrg.Lnext, and eNew.Dst is a newly created vertex.
* eOrg and eNew will have the same left face.
*/
/* __gl_meshAddEdgeVertex( eOrg ) creates a new edge eNew such that
* eNew == eOrg.Lnext, and eNew.Dst is a newly created vertex.
* eOrg and eNew will have the same left face.
*/
static GLUhalfEdge __gl_meshAddEdgeVertex(GLUhalfEdge eOrg) {
GLUhalfEdge eNewSym;
GLUhalfEdge eNew = MakeEdge(eOrg);
@@ -468,11 +459,10 @@ class Mesh {
return eNew;
}
/* __gl_meshSplitEdge( eOrg ) splits eOrg into two edges eOrg and eNew,
* such that eNew == eOrg.Lnext. The new vertex is eOrg.Sym.Org == eNew.Org.
* eOrg and eNew will have the same left face.
*/
/* __gl_meshSplitEdge( eOrg ) splits eOrg into two edges eOrg and eNew,
* such that eNew == eOrg.Lnext. The new vertex is eOrg.Sym.Org == eNew.Org.
* eOrg and eNew will have the same left face.
*/
public static GLUhalfEdge __gl_meshSplitEdge(GLUhalfEdge eOrg) {
GLUhalfEdge eNew;
GLUhalfEdge tempHalfEdge = __gl_meshAddEdgeVertex(eOrg);
@@ -485,25 +475,24 @@ class Mesh {
/* Set the vertex and face information */
eOrg.Sym.Org = eNew.Org;
eNew.Sym.Org.anEdge = eNew.Sym; /* may have pointed to eOrg.Sym */
eNew.Sym.Org.anEdge = eNew.Sym; /* may have pointed to eOrg.Sym */
eNew.Sym.Lface = eOrg.Sym.Lface;
eNew.winding = eOrg.winding; /* copy old winding information */
eNew.winding = eOrg.winding; /* copy old winding information */
eNew.Sym.winding = eOrg.Sym.winding;
return eNew;
}
/* __gl_meshConnect( eOrg, eDst ) creates a new edge from eOrg.Sym.Org
* to eDst.Org, and returns the corresponding half-edge eNew.
* If eOrg.Lface == eDst.Lface, this splits one loop into two,
* and the newly created loop is eNew.Lface. Otherwise, two disjoint
* loops are merged into one, and the loop eDst.Lface is destroyed.
*
* If (eOrg == eDst), the new face will have only two edges.
* If (eOrg.Lnext == eDst), the old face is reduced to a single edge.
* If (eOrg.Lnext.Lnext == eDst), the old face is reduced to two edges.
*/
/* __gl_meshConnect( eOrg, eDst ) creates a new edge from eOrg.Sym.Org
* to eDst.Org, and returns the corresponding half-edge eNew.
* If eOrg.Lface == eDst.Lface, this splits one loop into two,
* and the newly created loop is eNew.Lface. Otherwise, two disjoint
* loops are merged into one, and the loop eDst.Lface is destroyed.
*
* If (eOrg == eDst), the new face will have only two edges.
* If (eOrg.Lnext == eDst), the old face is reduced to a single edge.
* If (eOrg.Lnext.Lnext == eDst), the old face is reduced to two edges.
*/
static GLUhalfEdge __gl_meshConnect(GLUhalfEdge eOrg, GLUhalfEdge eDst) {
GLUhalfEdge eNewSym;
boolean joiningLoops = false;
@@ -538,16 +527,15 @@ class Mesh {
return eNew;
}
/******************** Other Operations **********************/
/* __gl_meshZapFace( fZap ) destroys a face and removes it from the
* global face list. All edges of fZap will have a null pointer as their
* left face. Any edges which also have a null pointer as their right face
* are deleted entirely (along with any isolated vertices this produces).
* An entire mesh can be deleted by zapping its faces, one at a time,
* in any order. Zapped faces cannot be used in further mesh operations!
*/
/* __gl_meshZapFace( fZap ) destroys a face and removes it from the
* global face list. All edges of fZap will have a null pointer as their
* left face. Any edges which also have a null pointer as their right face
* are deleted entirely (along with any isolated vertices this produces).
* An entire mesh can be deleted by zapping its faces, one at a time,
* in any order. Zapped faces cannot be used in further mesh operations!
*/
static void __gl_meshZapFace(GLUface fZap) {
GLUhalfEdge eStart = fZap.anEdge;
GLUhalfEdge e, eNext, eSym;
@@ -589,10 +577,9 @@ class Mesh {
fPrev.next = fNext;
}
/* __gl_meshNewMesh() creates a new mesh with no edges, no vertices,
* and no loops (what we usually call a "face").
*/
/* __gl_meshNewMesh() creates a new mesh with no edges, no vertices,
* and no loops (what we usually call a "face").
*/
public static GLUmesh __gl_meshNewMesh() {
GLUvertex v;
GLUface f;
@@ -637,10 +624,9 @@ class Mesh {
return mesh;
}
/* __gl_meshUnion( mesh1, mesh2 ) forms the union of all structures in
* both meshes, and returns the new mesh (the old meshes are destroyed).
*/
/* __gl_meshUnion( mesh1, mesh2 ) forms the union of all structures in
* both meshes, and returns the new mesh (the old meshes are destroyed).
*/
static GLUmesh __gl_meshUnion(GLUmesh mesh1, GLUmesh mesh2) {
GLUface f1 = mesh1.fHead;
GLUvertex v1 = mesh1.vHead;
@@ -674,9 +660,8 @@ class Mesh {
return mesh1;
}
/* __gl_meshDeleteMesh( mesh ) will free all storage for any valid mesh.
*/
/* __gl_meshDeleteMesh( mesh ) will free all storage for any valid mesh.
*/
static void __gl_meshDeleteMeshZap(GLUmesh mesh) {
GLUface fHead = mesh.fHead;
@@ -686,8 +671,8 @@ class Mesh {
assert (mesh.vHead.next == mesh.vHead);
}
/* __gl_meshDeleteMesh( mesh ) will free all storage for any valid mesh.
*/
/* __gl_meshDeleteMesh( mesh ) will free all storage for any valid mesh.
*/
public static void __gl_meshDeleteMesh(GLUmesh mesh) {
GLUface f, fNext;
GLUvertex v, vNext;
@@ -707,8 +692,8 @@ class Mesh {
}
}
/* __gl_meshCheckMesh( mesh ) checks a mesh for self-consistency.
*/
/* __gl_meshCheckMesh( mesh ) checks a mesh for self-consistency.
*/
public static void __gl_meshCheckMesh(GLUmesh mesh) {
GLUface fHead = mesh.fHead;
GLUvertex vHead = mesh.vHead;
@@ -760,7 +745,9 @@ class Mesh {
assert (e.Sym.next == ePrev.Sym
&& e.Sym == mesh.eHeadSym
&& e.Sym.Sym == e
&& e.Org == null && e.Sym.Org == null
&& e.Lface == null && e.Sym.Lface == null);
&& e.Org == null
&& e.Sym.Org == null
&& e.Lface == null
&& e.Sym.Lface == null);
}
}
@@ -31,82 +31,81 @@
*/
/*
* Portions Copyright (C) 2003-2006 Sun Microsystems, Inc.
* All rights reserved.
*/
* Portions Copyright (C) 2003-2006 Sun Microsystems, Inc.
* All rights reserved.
*/
/*
** License Applicability. Except to the extent portions of this file are
** made subject to an alternative license as permitted in the SGI Free
** Software License B, Version 1.1 (the "License"), the contents of this
** file are subject only to the provisions of the License. You may not use
** this file except in compliance with the License. You may obtain a copy
** of the License at Silicon Graphics, Inc., attn: Legal Services, 1600
** Amphitheatre Parkway, Mountain View, CA 94043-1351, or at:
**
** http://oss.sgi.com/projects/FreeB
**
** Note that, as provided in the License, the Software is distributed on an
** "AS IS" basis, with ALL EXPRESS AND IMPLIED WARRANTIES AND CONDITIONS
** DISCLAIMED, INCLUDING, WITHOUT LIMITATION, ANY IMPLIED WARRANTIES AND
** CONDITIONS OF MERCHANTABILITY, SATISFACTORY QUALITY, FITNESS FOR A
** PARTICULAR PURPOSE, AND NON-INFRINGEMENT.
**
** NOTE: The Original Code (as defined below) has been licensed to Sun
** Microsystems, Inc. ("Sun") under the SGI Free Software License B
** (Version 1.1), shown above ("SGI License"). Pursuant to Section
** 3.2(3) of the SGI License, Sun is distributing the Covered Code to
** you under an alternative license ("Alternative License"). This
** Alternative License includes all of the provisions of the SGI License
** except that Section 2.2 and 11 are omitted. Any differences between
** the Alternative License and the SGI License are offered solely by Sun
** and not by SGI.
**
** Original Code. The Original Code is: OpenGL Sample Implementation,
** Version 1.2.1, released January 26, 2000, developed by Silicon Graphics,
** Inc. The Original Code is Copyright (c) 1991-2000 Silicon Graphics, Inc.
** Copyright in any portions created by third parties is as indicated
** elsewhere herein. All Rights Reserved.
**
** Additional Notice Provisions: The application programming interfaces
** established by SGI in conjunction with the Original Code are The
** OpenGL(R) Graphics System: A Specification (Version 1.2.1), released
** April 1, 1999; The OpenGL(R) Graphics System Utility Library (Version
** 1.3), released November 4, 1998; and OpenGL(R) Graphics with the X
** Window System(R) (Version 1.3), released October 19, 1998. This software
** was created using the OpenGL(R) version 1.2.1 Sample Implementation
** published by SGI, but has not been independently verified as being
** compliant with the OpenGL(R) version 1.2.1 Specification.
**
** Author: Eric Veach, July 1994
** Java Port: Pepijn Van Eeckhoudt, July 2003
** Java Port: Nathan Parker Burg, August 2003
*/
** License Applicability. Except to the extent portions of this file are
** made subject to an alternative license as permitted in the SGI Free
** Software License B, Version 1.1 (the "License"), the contents of this
** file are subject only to the provisions of the License. You may not use
** this file except in compliance with the License. You may obtain a copy
** of the License at Silicon Graphics, Inc., attn: Legal Services, 1600
** Amphitheatre Parkway, Mountain View, CA 94043-1351, or at:
**
** http://oss.sgi.com/projects/FreeB
**
** Note that, as provided in the License, the Software is distributed on an
** "AS IS" basis, with ALL EXPRESS AND IMPLIED WARRANTIES AND CONDITIONS
** DISCLAIMED, INCLUDING, WITHOUT LIMITATION, ANY IMPLIED WARRANTIES AND
** CONDITIONS OF MERCHANTABILITY, SATISFACTORY QUALITY, FITNESS FOR A
** PARTICULAR PURPOSE, AND NON-INFRINGEMENT.
**
** NOTE: The Original Code (as defined below) has been licensed to Sun
** Microsystems, Inc. ("Sun") under the SGI Free Software License B
** (Version 1.1), shown above ("SGI License"). Pursuant to Section
** 3.2(3) of the SGI License, Sun is distributing the Covered Code to
** you under an alternative license ("Alternative License"). This
** Alternative License includes all of the provisions of the SGI License
** except that Section 2.2 and 11 are omitted. Any differences between
** the Alternative License and the SGI License are offered solely by Sun
** and not by SGI.
**
** Original Code. The Original Code is: OpenGL Sample Implementation,
** Version 1.2.1, released January 26, 2000, developed by Silicon Graphics,
** Inc. The Original Code is Copyright (c) 1991-2000 Silicon Graphics, Inc.
** Copyright in any portions created by third parties is as indicated
** elsewhere herein. All Rights Reserved.
**
** Additional Notice Provisions: The application programming interfaces
** established by SGI in conjunction with the Original Code are The
** OpenGL(R) Graphics System: A Specification (Version 1.2.1), released
** April 1, 1999; The OpenGL(R) Graphics System Utility Library (Version
** 1.3), released November 4, 1998; and OpenGL(R) Graphics with the X
** Window System(R) (Version 1.3), released October 19, 1998. This software
** was created using the OpenGL(R) version 1.2.1 Sample Implementation
** published by SGI, but has not been independently verified as being
** compliant with the OpenGL(R) version 1.2.1 Specification.
**
** Author: Eric Veach, July 1994
** Java Port: Pepijn Van Eeckhoudt, July 2003
** Java Port: Nathan Parker Burg, August 2003
*/
package org.lwjglx.util.glu.tessellation;
import org.lwjglx.util.glu.GLU;
class Normal {
private Normal() {
}
private Normal() {}
static boolean SLANTED_SWEEP;
static double S_UNIT_X; /* Pre-normalized */
static double S_UNIT_X; /* Pre-normalized */
static double S_UNIT_Y;
private static final boolean TRUE_PROJECT = false;
static {
if (SLANTED_SWEEP) {
/* The "feature merging" is not intended to be complete. There are
* special cases where edges are nearly parallel to the sweep line
* which are not implemented. The algorithm should still behave
* robustly (ie. produce a reasonable tesselation) in the presence
* of such edges, however it may miss features which could have been
* merged. We could minimize this effect by choosing the sweep line
* direction to be something unusual (ie. not parallel to one of the
* coordinate axes).
*/
S_UNIT_X = 0.50941539564955385; /* Pre-normalized */
/* The "feature merging" is not intended to be complete. There are
* special cases where edges are nearly parallel to the sweep line
* which are not implemented. The algorithm should still behave
* robustly (ie. produce a reasonable tesselation) in the presence
* of such edges, however it may miss features which could have been
* merged. We could minimize this effect by choosing the sweep line
* direction to be something unusual (ie. not parallel to one of the
* coordinate axes).
*/
S_UNIT_X = 0.50941539564955385; /* Pre-normalized */
S_UNIT_Y = 0.86052074622010633;
} else {
S_UNIT_X = 1.0;
@@ -173,7 +172,7 @@ class Normal {
}
}
/* Find two vertices separated by at least 1/sqrt(3) of the maximum
/* Find two vertices separated by at least 1/sqrt(3) of the maximum
* distance between any two vertices
*/
i = 0;
@@ -184,14 +183,14 @@ class Normal {
i = 2;
}
if (minVal[i] >= maxVal[i]) {
/* All vertices are the same -- normal doesn't matter */
/* All vertices are the same -- normal doesn't matter */
norm[0] = 0;
norm[1] = 0;
norm[2] = 1;
return;
}
/* Look for a third vertex which forms the triangle with maximum area
/* Look for a third vertex which forms the triangle with maximum area
* (Length of normal == twice the triangle area)
*/
maxLen2 = 0;
@@ -217,7 +216,7 @@ class Normal {
}
if (maxLen2 <= 0) {
/* All points lie on a single line -- any decent normal will do */
/* All points lie on a single line -- any decent normal will do */
norm[0] = norm[1] = norm[2] = 0;
norm[LongAxis(d1)] = 1;
}
@@ -229,9 +228,9 @@ class Normal {
GLUvertex v, vHead = tess.mesh.vHead;
GLUhalfEdge e;
/* When we compute the normal automatically, we choose the orientation
* so that the the sum of the signed areas of all contours is non-negative.
*/
/* When we compute the normal automatically, we choose the orientation
* so that the the sum of the signed areas of all contours is non-negative.
*/
area = 0;
for (f = fHead.next; f != fHead; f = f.next) {
e = f.anEdge;
@@ -242,7 +241,7 @@ class Normal {
} while (e != f.anEdge);
}
if (area < 0) {
/* Reverse the orientation by flipping all the t-coordinates */
/* Reverse the orientation by flipping all the t-coordinates */
for (v = vHead.next; v != vHead; v = v.next) {
v.t = -v.t;
}
@@ -252,9 +251,9 @@ class Normal {
}
}
/* Determine the polygon normal and project vertices onto the plane
* of the polygon.
*/
/* Determine the polygon normal and project vertices onto the plane
* of the polygon.
*/
public static void __gl_projectPolygon(GLUtessellatorImpl tess) {
GLUvertex v, vHead = tess.mesh.vHead;
double w;
@@ -275,29 +274,29 @@ class Normal {
i = LongAxis(norm);
if (TRUE_PROJECT) {
/* Choose the initial sUnit vector to be approximately perpendicular
* to the normal.
*/
/* Choose the initial sUnit vector to be approximately perpendicular
* to the normal.
*/
Normalize(norm);
sUnit[i] = 0;
sUnit[(i + 1) % 3] = S_UNIT_X;
sUnit[(i + 2) % 3] = S_UNIT_Y;
/* Now make it exactly perpendicular */
/* Now make it exactly perpendicular */
w = Dot(sUnit, norm);
sUnit[0] -= w * norm[0];
sUnit[1] -= w * norm[1];
sUnit[2] -= w * norm[2];
Normalize(sUnit);
/* Choose tUnit so that (sUnit,tUnit,norm) form a right-handed frame */
/* Choose tUnit so that (sUnit,tUnit,norm) form a right-handed frame */
tUnit[0] = norm[1] * sUnit[2] - norm[2] * sUnit[1];
tUnit[1] = norm[2] * sUnit[0] - norm[0] * sUnit[2];
tUnit[2] = norm[0] * sUnit[1] - norm[1] * sUnit[0];
Normalize(tUnit);
} else {
/* Project perpendicular to a coordinate axis -- better numerically */
/* Project perpendicular to a coordinate axis -- better numerically */
sUnit[i] = 0;
sUnit[(i + 1) % 3] = S_UNIT_X;
sUnit[(i + 2) % 3] = S_UNIT_Y;
@@ -307,7 +306,7 @@ class Normal {
tUnit[(i + 2) % 3] = (norm[i] > 0) ? S_UNIT_X : -S_UNIT_X;
}
/* Project the vertices onto the sweep plane */
/* Project the vertices onto the sweep plane */
for (v = vHead.next; v != vHead; v = v.next) {
v.s = Dot(v.coords, sUnit);
v.t = Dot(v.coords, tUnit);
@@ -31,57 +31,57 @@
*/
/*
* Portions Copyright (C) 2003-2006 Sun Microsystems, Inc.
* All rights reserved.
*/
* Portions Copyright (C) 2003-2006 Sun Microsystems, Inc.
* All rights reserved.
*/
/*
** License Applicability. Except to the extent portions of this file are
** made subject to an alternative license as permitted in the SGI Free
** Software License B, Version 1.1 (the "License"), the contents of this
** file are subject only to the provisions of the License. You may not use
** this file except in compliance with the License. You may obtain a copy
** of the License at Silicon Graphics, Inc., attn: Legal Services, 1600
** Amphitheatre Parkway, Mountain View, CA 94043-1351, or at:
**
** http://oss.sgi.com/projects/FreeB
**
** Note that, as provided in the License, the Software is distributed on an
** "AS IS" basis, with ALL EXPRESS AND IMPLIED WARRANTIES AND CONDITIONS
** DISCLAIMED, INCLUDING, WITHOUT LIMITATION, ANY IMPLIED WARRANTIES AND
** CONDITIONS OF MERCHANTABILITY, SATISFACTORY QUALITY, FITNESS FOR A
** PARTICULAR PURPOSE, AND NON-INFRINGEMENT.
**
** NOTE: The Original Code (as defined below) has been licensed to Sun
** Microsystems, Inc. ("Sun") under the SGI Free Software License B
** (Version 1.1), shown above ("SGI License"). Pursuant to Section
** 3.2(3) of the SGI License, Sun is distributing the Covered Code to
** you under an alternative license ("Alternative License"). This
** Alternative License includes all of the provisions of the SGI License
** except that Section 2.2 and 11 are omitted. Any differences between
** the Alternative License and the SGI License are offered solely by Sun
** and not by SGI.
**
** Original Code. The Original Code is: OpenGL Sample Implementation,
** Version 1.2.1, released January 26, 2000, developed by Silicon Graphics,
** Inc. The Original Code is Copyright (c) 1991-2000 Silicon Graphics, Inc.
** Copyright in any portions created by third parties is as indicated
** elsewhere herein. All Rights Reserved.
**
** Additional Notice Provisions: The application programming interfaces
** established by SGI in conjunction with the Original Code are The
** OpenGL(R) Graphics System: A Specification (Version 1.2.1), released
** April 1, 1999; The OpenGL(R) Graphics System Utility Library (Version
** 1.3), released November 4, 1998; and OpenGL(R) Graphics with the X
** Window System(R) (Version 1.3), released October 19, 1998. This software
** was created using the OpenGL(R) version 1.2.1 Sample Implementation
** published by SGI, but has not been independently verified as being
** compliant with the OpenGL(R) version 1.2.1 Specification.
**
** Author: Eric Veach, July 1994
** Java Port: Pepijn Van Eeckhoudt, July 2003
** Java Port: Nathan Parker Burg, August 2003
*/
** License Applicability. Except to the extent portions of this file are
** made subject to an alternative license as permitted in the SGI Free
** Software License B, Version 1.1 (the "License"), the contents of this
** file are subject only to the provisions of the License. You may not use
** this file except in compliance with the License. You may obtain a copy
** of the License at Silicon Graphics, Inc., attn: Legal Services, 1600
** Amphitheatre Parkway, Mountain View, CA 94043-1351, or at:
**
** http://oss.sgi.com/projects/FreeB
**
** Note that, as provided in the License, the Software is distributed on an
** "AS IS" basis, with ALL EXPRESS AND IMPLIED WARRANTIES AND CONDITIONS
** DISCLAIMED, INCLUDING, WITHOUT LIMITATION, ANY IMPLIED WARRANTIES AND
** CONDITIONS OF MERCHANTABILITY, SATISFACTORY QUALITY, FITNESS FOR A
** PARTICULAR PURPOSE, AND NON-INFRINGEMENT.
**
** NOTE: The Original Code (as defined below) has been licensed to Sun
** Microsystems, Inc. ("Sun") under the SGI Free Software License B
** (Version 1.1), shown above ("SGI License"). Pursuant to Section
** 3.2(3) of the SGI License, Sun is distributing the Covered Code to
** you under an alternative license ("Alternative License"). This
** Alternative License includes all of the provisions of the SGI License
** except that Section 2.2 and 11 are omitted. Any differences between
** the Alternative License and the SGI License are offered solely by Sun
** and not by SGI.
**
** Original Code. The Original Code is: OpenGL Sample Implementation,
** Version 1.2.1, released January 26, 2000, developed by Silicon Graphics,
** Inc. The Original Code is Copyright (c) 1991-2000 Silicon Graphics, Inc.
** Copyright in any portions created by third parties is as indicated
** elsewhere herein. All Rights Reserved.
**
** Additional Notice Provisions: The application programming interfaces
** established by SGI in conjunction with the Original Code are The
** OpenGL(R) Graphics System: A Specification (Version 1.2.1), released
** April 1, 1999; The OpenGL(R) Graphics System Utility Library (Version
** 1.3), released November 4, 1998; and OpenGL(R) Graphics with the X
** Window System(R) (Version 1.3), released October 19, 1998. This software
** was created using the OpenGL(R) version 1.2.1 Sample Implementation
** published by SGI, but has not been independently verified as being
** compliant with the OpenGL(R) version 1.2.1 Specification.
**
** Author: Eric Veach, July 1994
** Java Port: Pepijn Van Eeckhoudt, July 2003
** Java Port: Nathan Parker Burg, August 2003
*/
package org.lwjglx.util.glu.tessellation;
abstract class PriorityQ {
@@ -101,12 +101,12 @@ abstract class PriorityQ {
}
// #ifdef FOR_TRITE_TEST_PROGRAM
// private static boolean LEQ(PriorityQCommon.Leq leq, Object x,Object y) {
// return pq.leq.leq(x,y);
// }
// #else
/* Violates modularity, but a little faster */
// #include "geom.h"
// private static boolean LEQ(PriorityQCommon.Leq leq, Object x,Object y) {
// return pq.leq.leq(x,y);
// }
// #else
/* Violates modularity, but a little faster */
// #include "geom.h"
public static boolean LEQ(Leq leq, Object x, Object y) {
return Geom.VertLeq((GLUvertex) x, (GLUvertex) y);
}
@@ -128,5 +128,5 @@ abstract class PriorityQ {
abstract Object pqMinimum();
abstract boolean pqIsEmpty();
// #endif
// #endif
}
@@ -31,61 +31,59 @@
*/
/*
* Portions Copyright (C) 2003-2006 Sun Microsystems, Inc.
* All rights reserved.
*/
* Portions Copyright (C) 2003-2006 Sun Microsystems, Inc.
* All rights reserved.
*/
/*
** License Applicability. Except to the extent portions of this file are
** made subject to an alternative license as permitted in the SGI Free
** Software License B, Version 1.1 (the "License"), the contents of this
** file are subject only to the provisions of the License. You may not use
** this file except in compliance with the License. You may obtain a copy
** of the License at Silicon Graphics, Inc., attn: Legal Services, 1600
** Amphitheatre Parkway, Mountain View, CA 94043-1351, or at:
**
** http://oss.sgi.com/projects/FreeB
**
** Note that, as provided in the License, the Software is distributed on an
** "AS IS" basis, with ALL EXPRESS AND IMPLIED WARRANTIES AND CONDITIONS
** DISCLAIMED, INCLUDING, WITHOUT LIMITATION, ANY IMPLIED WARRANTIES AND
** CONDITIONS OF MERCHANTABILITY, SATISFACTORY QUALITY, FITNESS FOR A
** PARTICULAR PURPOSE, AND NON-INFRINGEMENT.
**
** NOTE: The Original Code (as defined below) has been licensed to Sun
** Microsystems, Inc. ("Sun") under the SGI Free Software License B
** (Version 1.1), shown above ("SGI License"). Pursuant to Section
** 3.2(3) of the SGI License, Sun is distributing the Covered Code to
** you under an alternative license ("Alternative License"). This
** Alternative License includes all of the provisions of the SGI License
** except that Section 2.2 and 11 are omitted. Any differences between
** the Alternative License and the SGI License are offered solely by Sun
** and not by SGI.
**
** Original Code. The Original Code is: OpenGL Sample Implementation,
** Version 1.2.1, released January 26, 2000, developed by Silicon Graphics,
** Inc. The Original Code is Copyright (c) 1991-2000 Silicon Graphics, Inc.
** Copyright in any portions created by third parties is as indicated
** elsewhere herein. All Rights Reserved.
**
** Additional Notice Provisions: The application programming interfaces
** established by SGI in conjunction with the Original Code are The
** OpenGL(R) Graphics System: A Specification (Version 1.2.1), released
** April 1, 1999; The OpenGL(R) Graphics System Utility Library (Version
** 1.3), released November 4, 1998; and OpenGL(R) Graphics with the X
** Window System(R) (Version 1.3), released October 19, 1998. This software
** was created using the OpenGL(R) version 1.2.1 Sample Implementation
** published by SGI, but has not been independently verified as being
** compliant with the OpenGL(R) version 1.2.1 Specification.
**
** Author: Eric Veach, July 1994
** Java Port: Pepijn Van Eeckhoudt, July 2003
** Java Port: Nathan Parker Burg, August 2003
*/
** License Applicability. Except to the extent portions of this file are
** made subject to an alternative license as permitted in the SGI Free
** Software License B, Version 1.1 (the "License"), the contents of this
** file are subject only to the provisions of the License. You may not use
** this file except in compliance with the License. You may obtain a copy
** of the License at Silicon Graphics, Inc., attn: Legal Services, 1600
** Amphitheatre Parkway, Mountain View, CA 94043-1351, or at:
**
** http://oss.sgi.com/projects/FreeB
**
** Note that, as provided in the License, the Software is distributed on an
** "AS IS" basis, with ALL EXPRESS AND IMPLIED WARRANTIES AND CONDITIONS
** DISCLAIMED, INCLUDING, WITHOUT LIMITATION, ANY IMPLIED WARRANTIES AND
** CONDITIONS OF MERCHANTABILITY, SATISFACTORY QUALITY, FITNESS FOR A
** PARTICULAR PURPOSE, AND NON-INFRINGEMENT.
**
** NOTE: The Original Code (as defined below) has been licensed to Sun
** Microsystems, Inc. ("Sun") under the SGI Free Software License B
** (Version 1.1), shown above ("SGI License"). Pursuant to Section
** 3.2(3) of the SGI License, Sun is distributing the Covered Code to
** you under an alternative license ("Alternative License"). This
** Alternative License includes all of the provisions of the SGI License
** except that Section 2.2 and 11 are omitted. Any differences between
** the Alternative License and the SGI License are offered solely by Sun
** and not by SGI.
**
** Original Code. The Original Code is: OpenGL Sample Implementation,
** Version 1.2.1, released January 26, 2000, developed by Silicon Graphics,
** Inc. The Original Code is Copyright (c) 1991-2000 Silicon Graphics, Inc.
** Copyright in any portions created by third parties is as indicated
** elsewhere herein. All Rights Reserved.
**
** Additional Notice Provisions: The application programming interfaces
** established by SGI in conjunction with the Original Code are The
** OpenGL(R) Graphics System: A Specification (Version 1.2.1), released
** April 1, 1999; The OpenGL(R) Graphics System Utility Library (Version
** 1.3), released November 4, 1998; and OpenGL(R) Graphics with the X
** Window System(R) (Version 1.3), released October 19, 1998. This software
** was created using the OpenGL(R) version 1.2.1 Sample Implementation
** published by SGI, but has not been independently verified as being
** compliant with the OpenGL(R) version 1.2.1 Specification.
**
** Author: Eric Veach, July 1994
** Java Port: Pepijn Van Eeckhoudt, July 2003
** Java Port: Nathan Parker Burg, August 2003
*/
package org.lwjglx.util.glu.tessellation;
class PriorityQHeap extends PriorityQ {
PriorityQ.PQnode[] nodes;
PriorityQ.PQhandleElem[] handles;
@@ -94,8 +92,8 @@ class PriorityQHeap extends PriorityQ {
boolean initialized;
PriorityQ.Leq leq;
/* really __gl_pqHeapNewPriorityQ */
PriorityQHeap(PriorityQ.Leq leq) {
/* really __gl_pqHeapNewPriorityQ */
PriorityQHeap(PriorityQ.Leq leq) {
size = 0;
max = PriorityQ.INIT_SIZE;
nodes = new PriorityQ.PQnode[PriorityQ.INIT_SIZE + 1];
@@ -110,11 +108,11 @@ PriorityQHeap(PriorityQ.Leq leq) {
freeList = 0;
this.leq = leq;
nodes[1].handle = 1; /* so that Minimum() returns NULL */
nodes[1].handle = 1; /* so that Minimum() returns NULL */
handles[1].key = null;
}
/* really __gl_pqHeapDeletePriorityQ */
/* really __gl_pqHeapDeletePriorityQ */
void pqDeletePriorityQ() {
handles = null;
nodes = null;
@@ -127,10 +125,9 @@ PriorityQHeap(PriorityQ.Leq leq) {
int child;
hCurr = n[curr].handle;
for (; ;) {
for (; ; ) {
child = curr << 1;
if (child < size && LEQ(leq, h[n[child + 1].handle].key,
h[n[child].handle].key)) {
if (child < size && LEQ(leq, h[n[child + 1].handle].key, h[n[child].handle].key)) {
++child;
}
@@ -148,7 +145,6 @@ PriorityQHeap(PriorityQ.Leq leq) {
}
}
void FloatUp(int curr) {
PriorityQ.PQnode[] n = nodes;
PriorityQ.PQhandleElem[] h = handles;
@@ -156,7 +152,7 @@ PriorityQHeap(PriorityQ.Leq leq) {
int parent;
hCurr = n[curr].handle;
for (; ;) {
for (; ; ) {
parent = curr >> 1;
hParent = n[parent].handle;
if (parent == 0 || LEQ(leq, h[hParent].key, h[hCurr].key)) {
@@ -170,7 +166,7 @@ PriorityQHeap(PriorityQ.Leq leq) {
}
}
/* really __gl_pqHeapInit */
/* really __gl_pqHeapInit */
boolean pqInit() {
int i;
@@ -184,8 +180,8 @@ PriorityQHeap(PriorityQ.Leq leq) {
return true;
}
/* really __gl_pqHeapInsert */
/* returns LONG_MAX iff out of memory */
/* really __gl_pqHeapInsert */
/* returns LONG_MAX iff out of memory */
int pqInsert(Object keyNew) {
int curr;
int free;
@@ -197,21 +193,23 @@ PriorityQHeap(PriorityQ.Leq leq) {
/* If the heap overflows, double its size. */
max <<= 1;
// pq->nodes = (PQnode *)memRealloc( pq->nodes, (size_t) ((pq->max + 1) * sizeof( pq->nodes[0] )));
// pq->nodes = (PQnode *)memRealloc( pq->nodes, (size_t) ((pq->max + 1) * sizeof( pq->nodes[0]
// )));
PriorityQ.PQnode[] pqNodes = new PriorityQ.PQnode[max + 1];
System.arraycopy( nodes, 0, pqNodes, 0, nodes.length );
System.arraycopy(nodes, 0, pqNodes, 0, nodes.length);
for (int i = nodes.length; i < pqNodes.length; i++) {
pqNodes[i] = new PQnode();
}
nodes = pqNodes;
if (nodes == null) {
nodes = saveNodes; /* restore ptr to free upon return */
nodes = saveNodes; /* restore ptr to free upon return */
return Integer.MAX_VALUE;
}
// pq->handles = (PQhandleElem *)memRealloc( pq->handles,(size_t)((pq->max + 1) * sizeof( pq->handles[0] )));
// pq->handles = (PQhandleElem *)memRealloc( pq->handles,(size_t)((pq->max + 1) * sizeof(
// pq->handles[0] )));
PriorityQ.PQhandleElem[] pqHandles = new PriorityQ.PQhandleElem[max + 1];
System.arraycopy( handles, 0, pqHandles, 0, handles.length );
System.arraycopy(handles, 0, pqHandles, 0, handles.length);
for (int i = handles.length; i < pqHandles.length; i++) {
pqHandles[i] = new PQhandleElem();
}
@@ -240,7 +238,7 @@ PriorityQHeap(PriorityQ.Leq leq) {
return free;
}
/* really __gl_pqHeapExtractMin */
/* really __gl_pqHeapExtractMin */
Object pqExtractMin() {
PriorityQ.PQnode[] n = nodes;
PriorityQ.PQhandleElem[] h = handles;
@@ -262,7 +260,7 @@ PriorityQHeap(PriorityQ.Leq leq) {
return min;
}
/* really __gl_pqHeapDelete */
/* really __gl_pqHeapDelete */
void pqDelete(int hCurr) {
PriorityQ.PQnode[] n = nodes;
PriorityQ.PQhandleElem[] h = handles;
@@ -31,56 +31,54 @@
*/
/*
** License Applicability. Except to the extent portions of this file are
** made subject to an alternative license as permitted in the SGI Free
** Software License B, Version 1.1 (the "License"), the contents of this
** file are subject only to the provisions of the License. You may not use
** this file except in compliance with the License. You may obtain a copy
** of the License at Silicon Graphics, Inc., attn: Legal Services, 1600
** Amphitheatre Parkway, Mountain View, CA 94043-1351, or at:
**
** http://oss.sgi.com/projects/FreeB
**
** Note that, as provided in the License, the Software is distributed on an
** "AS IS" basis, with ALL EXPRESS AND IMPLIED WARRANTIES AND CONDITIONS
** DISCLAIMED, INCLUDING, WITHOUT LIMITATION, ANY IMPLIED WARRANTIES AND
** CONDITIONS OF MERCHANTABILITY, SATISFACTORY QUALITY, FITNESS FOR A
** PARTICULAR PURPOSE, AND NON-INFRINGEMENT.
**
** NOTE: The Original Code (as defined below) has been licensed to Sun
** Microsystems, Inc. ("Sun") under the SGI Free Software License B
** (Version 1.1), shown above ("SGI License"). Pursuant to Section
** 3.2(3) of the SGI License, Sun is distributing the Covered Code to
** you under an alternative license ("Alternative License"). This
** Alternative License includes all of the provisions of the SGI License
** except that Section 2.2 and 11 are omitted. Any differences between
** the Alternative License and the SGI License are offered solely by Sun
** and not by SGI.
**
** Original Code. The Original Code is: OpenGL Sample Implementation,
** Version 1.2.1, released January 26, 2000, developed by Silicon Graphics,
** Inc. The Original Code is Copyright (c) 1991-2000 Silicon Graphics, Inc.
** Copyright in any portions created by third parties is as indicated
** elsewhere herein. All Rights Reserved.
**
** Additional Notice Provisions: The application programming interfaces
** established by SGI in conjunction with the Original Code are The
** OpenGL(R) Graphics System: A Specification (Version 1.2.1), released
** April 1, 1999; The OpenGL(R) Graphics System Utility Library (Version
** 1.3), released November 4, 1998; and OpenGL(R) Graphics with the X
** Window System(R) (Version 1.3), released October 19, 1998. This software
** was created using the OpenGL(R) version 1.2.1 Sample Implementation
** published by SGI, but has not been independently verified as being
** compliant with the OpenGL(R) version 1.2.1 Specification.
**
** Author: Eric Veach, July 1994
** Java Port: Pepijn Van Eeckhoudt, July 2003
** Java Port: Nathan Parker Burg, August 2003
*/
** License Applicability. Except to the extent portions of this file are
** made subject to an alternative license as permitted in the SGI Free
** Software License B, Version 1.1 (the "License"), the contents of this
** file are subject only to the provisions of the License. You may not use
** this file except in compliance with the License. You may obtain a copy
** of the License at Silicon Graphics, Inc., attn: Legal Services, 1600
** Amphitheatre Parkway, Mountain View, CA 94043-1351, or at:
**
** http://oss.sgi.com/projects/FreeB
**
** Note that, as provided in the License, the Software is distributed on an
** "AS IS" basis, with ALL EXPRESS AND IMPLIED WARRANTIES AND CONDITIONS
** DISCLAIMED, INCLUDING, WITHOUT LIMITATION, ANY IMPLIED WARRANTIES AND
** CONDITIONS OF MERCHANTABILITY, SATISFACTORY QUALITY, FITNESS FOR A
** PARTICULAR PURPOSE, AND NON-INFRINGEMENT.
**
** NOTE: The Original Code (as defined below) has been licensed to Sun
** Microsystems, Inc. ("Sun") under the SGI Free Software License B
** (Version 1.1), shown above ("SGI License"). Pursuant to Section
** 3.2(3) of the SGI License, Sun is distributing the Covered Code to
** you under an alternative license ("Alternative License"). This
** Alternative License includes all of the provisions of the SGI License
** except that Section 2.2 and 11 are omitted. Any differences between
** the Alternative License and the SGI License are offered solely by Sun
** and not by SGI.
**
** Original Code. The Original Code is: OpenGL Sample Implementation,
** Version 1.2.1, released January 26, 2000, developed by Silicon Graphics,
** Inc. The Original Code is Copyright (c) 1991-2000 Silicon Graphics, Inc.
** Copyright in any portions created by third parties is as indicated
** elsewhere herein. All Rights Reserved.
**
** Additional Notice Provisions: The application programming interfaces
** established by SGI in conjunction with the Original Code are The
** OpenGL(R) Graphics System: A Specification (Version 1.2.1), released
** April 1, 1999; The OpenGL(R) Graphics System Utility Library (Version
** 1.3), released November 4, 1998; and OpenGL(R) Graphics with the X
** Window System(R) (Version 1.3), released October 19, 1998. This software
** was created using the OpenGL(R) version 1.2.1 Sample Implementation
** published by SGI, but has not been independently verified as being
** compliant with the OpenGL(R) version 1.2.1 Specification.
**
** Author: Eric Veach, July 1994
** Java Port: Pepijn Van Eeckhoudt, July 2003
** Java Port: Nathan Parker Burg, August 2003
*/
package org.lwjglx.util.glu.tessellation;
class PriorityQSort extends PriorityQ {
PriorityQHeap heap;
Object[] keys;
@@ -104,7 +102,7 @@ class PriorityQSort extends PriorityQ {
this.leq = leq;
}
/* really __gl_pqSortDeletePriorityQ */
/* really __gl_pqSortDeletePriorityQ */
void pqDeletePriorityQ() {
if (heap != null) heap.pqDeletePriorityQ();
order = null;
@@ -131,7 +129,7 @@ class PriorityQSort extends PriorityQ {
int p, r;
}
/* really __gl_pqSortInit */
/* really __gl_pqSortInit */
boolean pqInit() {
int p, r, i, j;
int piv;
@@ -147,10 +145,10 @@ class PriorityQSort extends PriorityQ {
* the handles we have returned are still valid.
*/
order = new int[size + 1];
/* the previous line is a patch to compensate for the fact that IBM */
/* machines return a null on a malloc of zero bytes (unlike SGI), */
/* so we have to put in this defense to guard against a memory */
/* fault four lines down. from [email protected]. */
/* the previous line is a patch to compensate for the fact that IBM */
/* machines return a null on a malloc of zero bytes (unlike SGI), */
/* so we have to put in this defense to guard against a memory */
/* fault four lines down. from [email protected]. */
p = 0;
r = size - 1;
for (piv = 0, i = p; i <= r; ++piv, ++i) {
@@ -168,7 +166,7 @@ class PriorityQSort extends PriorityQ {
p = stack[top].p;
r = stack[top].r;
while (r > p + 10) {
seed = Math.abs( seed * 1539415821 + 1 );
seed = Math.abs(seed * 1539415821 + 1);
i = p + seed % (r - p + 1);
piv = order[i];
order[i] = order[p];
@@ -184,7 +182,7 @@ class PriorityQSort extends PriorityQ {
} while (LT(leq, keys[order[j]], keys[piv]));
Swap(order, i, j);
} while (i < j);
Swap(order, i, j); /* Undo last swap */
Swap(order, i, j); /* Undo last swap */
if (i - p < r - j) {
stack[top].p = j + 1;
stack[top].r = r;
@@ -208,9 +206,9 @@ class PriorityQSort extends PriorityQ {
}
max = size;
initialized = true;
heap.pqInit(); /* always succeeds */
heap.pqInit(); /* always succeeds */
/* #ifndef NDEBUG
/* #ifndef NDEBUG
p = order;
r = p + size - 1;
for (i = p; i < r; ++i) {
@@ -221,8 +219,8 @@ class PriorityQSort extends PriorityQ {
return true;
}
/* really __gl_pqSortInsert */
/* returns LONG_MAX iff out of memory */
/* really __gl_pqSortInsert */
/* returns LONG_MAX iff out of memory */
int pqInsert(Object keyNew) {
int curr;
@@ -235,12 +233,12 @@ class PriorityQSort extends PriorityQ {
/* If the heap overflows, double its size. */
max <<= 1;
// pq->keys = (PQHeapKey *)memRealloc( pq->keys,(size_t)(pq->max * sizeof( pq->keys[0] )));
// pq->keys = (PQHeapKey *)memRealloc( pq->keys,(size_t)(pq->max * sizeof( pq->keys[0] )));
Object[] pqKeys = new Object[max];
System.arraycopy( keys, 0, pqKeys, 0, keys.length );
System.arraycopy(keys, 0, pqKeys, 0, keys.length);
keys = pqKeys;
if (keys == null) {
keys = saveKey; /* restore ptr to free upon return */
keys = saveKey; /* restore ptr to free upon return */
return Integer.MAX_VALUE;
}
}
@@ -251,7 +249,7 @@ class PriorityQSort extends PriorityQ {
return -(curr + 1);
}
/* really __gl_pqSortExtractMin */
/* really __gl_pqSortExtractMin */
Object pqExtractMin() {
Object sortMin, heapMin;
@@ -271,7 +269,7 @@ class PriorityQSort extends PriorityQ {
return sortMin;
}
/* really __gl_pqSortMinimum */
/* really __gl_pqSortMinimum */
Object pqMinimum() {
Object sortMin, heapMin;
@@ -288,12 +286,12 @@ class PriorityQSort extends PriorityQ {
return sortMin;
}
/* really __gl_pqSortIsEmpty */
/* really __gl_pqSortIsEmpty */
boolean pqIsEmpty() {
return (size == 0) && heap.pqIsEmpty();
}
/* really __gl_pqSortDelete */
/* really __gl_pqSortDelete */
void pqDelete(int curr) {
if (curr >= 0) {
heap.pqDelete(curr);
@@ -31,57 +31,57 @@
*/
/*
* Portions Copyright (C) 2003-2006 Sun Microsystems, Inc.
* All rights reserved.
*/
* Portions Copyright (C) 2003-2006 Sun Microsystems, Inc.
* All rights reserved.
*/
/*
** License Applicability. Except to the extent portions of this file are
** made subject to an alternative license as permitted in the SGI Free
** Software License B, Version 1.1 (the "License"), the contents of this
** file are subject only to the provisions of the License. You may not use
** this file except in compliance with the License. You may obtain a copy
** of the License at Silicon Graphics, Inc., attn: Legal Services, 1600
** Amphitheatre Parkway, Mountain View, CA 94043-1351, or at:
**
** http://oss.sgi.com/projects/FreeB
**
** Note that, as provided in the License, the Software is distributed on an
** "AS IS" basis, with ALL EXPRESS AND IMPLIED WARRANTIES AND CONDITIONS
** DISCLAIMED, INCLUDING, WITHOUT LIMITATION, ANY IMPLIED WARRANTIES AND
** CONDITIONS OF MERCHANTABILITY, SATISFACTORY QUALITY, FITNESS FOR A
** PARTICULAR PURPOSE, AND NON-INFRINGEMENT.
**
** NOTE: The Original Code (as defined below) has been licensed to Sun
** Microsystems, Inc. ("Sun") under the SGI Free Software License B
** (Version 1.1), shown above ("SGI License"). Pursuant to Section
** 3.2(3) of the SGI License, Sun is distributing the Covered Code to
** you under an alternative license ("Alternative License"). This
** Alternative License includes all of the provisions of the SGI License
** except that Section 2.2 and 11 are omitted. Any differences between
** the Alternative License and the SGI License are offered solely by Sun
** and not by SGI.
**
** Original Code. The Original Code is: OpenGL Sample Implementation,
** Version 1.2.1, released January 26, 2000, developed by Silicon Graphics,
** Inc. The Original Code is Copyright (c) 1991-2000 Silicon Graphics, Inc.
** Copyright in any portions created by third parties is as indicated
** elsewhere herein. All Rights Reserved.
**
** Additional Notice Provisions: The application programming interfaces
** established by SGI in conjunction with the Original Code are The
** OpenGL(R) Graphics System: A Specification (Version 1.2.1), released
** April 1, 1999; The OpenGL(R) Graphics System Utility Library (Version
** 1.3), released November 4, 1998; and OpenGL(R) Graphics with the X
** Window System(R) (Version 1.3), released October 19, 1998. This software
** was created using the OpenGL(R) version 1.2.1 Sample Implementation
** published by SGI, but has not been independently verified as being
** compliant with the OpenGL(R) version 1.2.1 Specification.
**
** Author: Eric Veach, July 1994
** Java Port: Pepijn Van Eeckhoudt, July 2003
** Java Port: Nathan Parker Burg, August 2003
*/
** License Applicability. Except to the extent portions of this file are
** made subject to an alternative license as permitted in the SGI Free
** Software License B, Version 1.1 (the "License"), the contents of this
** file are subject only to the provisions of the License. You may not use
** this file except in compliance with the License. You may obtain a copy
** of the License at Silicon Graphics, Inc., attn: Legal Services, 1600
** Amphitheatre Parkway, Mountain View, CA 94043-1351, or at:
**
** http://oss.sgi.com/projects/FreeB
**
** Note that, as provided in the License, the Software is distributed on an
** "AS IS" basis, with ALL EXPRESS AND IMPLIED WARRANTIES AND CONDITIONS
** DISCLAIMED, INCLUDING, WITHOUT LIMITATION, ANY IMPLIED WARRANTIES AND
** CONDITIONS OF MERCHANTABILITY, SATISFACTORY QUALITY, FITNESS FOR A
** PARTICULAR PURPOSE, AND NON-INFRINGEMENT.
**
** NOTE: The Original Code (as defined below) has been licensed to Sun
** Microsystems, Inc. ("Sun") under the SGI Free Software License B
** (Version 1.1), shown above ("SGI License"). Pursuant to Section
** 3.2(3) of the SGI License, Sun is distributing the Covered Code to
** you under an alternative license ("Alternative License"). This
** Alternative License includes all of the provisions of the SGI License
** except that Section 2.2 and 11 are omitted. Any differences between
** the Alternative License and the SGI License are offered solely by Sun
** and not by SGI.
**
** Original Code. The Original Code is: OpenGL Sample Implementation,
** Version 1.2.1, released January 26, 2000, developed by Silicon Graphics,
** Inc. The Original Code is Copyright (c) 1991-2000 Silicon Graphics, Inc.
** Copyright in any portions created by third parties is as indicated
** elsewhere herein. All Rights Reserved.
**
** Additional Notice Provisions: The application programming interfaces
** established by SGI in conjunction with the Original Code are The
** OpenGL(R) Graphics System: A Specification (Version 1.2.1), released
** April 1, 1999; The OpenGL(R) Graphics System Utility Library (Version
** 1.3), released November 4, 1998; and OpenGL(R) Graphics with the X
** Window System(R) (Version 1.3), released October 19, 1998. This software
** was created using the OpenGL(R) version 1.2.1 Sample Implementation
** published by SGI, but has not been independently verified as being
** compliant with the OpenGL(R) version 1.2.1 Specification.
**
** Author: Eric Veach, July 1994
** Java Port: Pepijn Van Eeckhoudt, July 2003
** Java Port: Nathan Parker Burg, August 2003
*/
package org.lwjglx.util.glu.tessellation;
import static org.lwjgl.opengl.GL11.*;
@@ -90,20 +90,18 @@ import static org.lwjglx.util.glu.GLU.*;
class Render {
private static final boolean USE_OPTIMIZED_CODE_PATH = false;
private Render() {
}
private Render() {}
private static final RenderFan renderFan = new RenderFan();
private static final RenderStrip renderStrip = new RenderStrip();
private static final RenderTriangle renderTriangle = new RenderTriangle();
/* This structure remembers the information we need about a primitive
* to be able to render it later, once we have determined which
* primitive is able to use the most triangles.
*/
/* This structure remembers the information we need about a primitive
* to be able to render it later, once we have determined which
* primitive is able to use the most triangles.
*/
private static class FaceCount {
private FaceCount() {
}
private FaceCount() {}
private FaceCount(long size, GLUhalfEdge eStart, renderCallBack render) {
this.size = size;
@@ -111,10 +109,11 @@ class Render {
this.render = render;
}
long size; /* number of triangles used */
GLUhalfEdge eStart; /* edge where this primitive starts */
long size; /* number of triangles used */
GLUhalfEdge eStart; /* edge where this primitive starts */
renderCallBack render;
};
}
;
private interface renderCallBack {
void render(GLUtessellatorImpl tess, GLUhalfEdge e, long size);
@@ -122,13 +121,13 @@ class Render {
/************************ Strips and Fans decomposition ******************/
/* __gl_renderMesh( tess, mesh ) takes a mesh and breaks it into triangle
* fans, strips, and separate triangles. A substantial effort is made
* to use as few rendering primitives as possible (ie. to make the fans
* and strips as large as possible).
*
* The rendering output is provided as callbacks (see the api).
*/
/* __gl_renderMesh( tess, mesh ) takes a mesh and breaks it into triangle
* fans, strips, and separate triangles. A substantial effort is made
* to use as few rendering primitives as possible (ie. to make the fans
* and strips as large as possible).
*
* The rendering output is provided as callbacks (see the api).
*/
public static void __gl_renderMesh(GLUtessellatorImpl tess, GLUmesh mesh) {
GLUface f;
@@ -155,7 +154,6 @@ class Render {
}
}
static void RenderMaximumFaceGroup(GLUtessellatorImpl tess, GLUface fOrig) {
/* We want to find the largest triangle fan or strip of unmarked faces
* which includes the given face fOrig. There are 3 possible fans
@@ -202,14 +200,13 @@ class Render {
max.render.render(tess, max.eStart, max.size);
}
/* Macros which keep track of faces we have marked temporarily, and allow
* us to backtrack when necessary. With triangle fans, this is not
* really necessary, since the only awkward case is a loop of triangles
* around a single origin vertex. However with strips the situation is
* more complicated, and we need a general tracking method like the
* one here.
*/
/* Macros which keep track of faces we have marked temporarily, and allow
* us to backtrack when necessary. With triangle fans, this is not
* really necessary, since the only awkward case is a loop of triangles
* around a single origin vertex. However with strips the situation is
* more complicated, and we need a general tracking method like the
* one here.
*/
private static boolean Marked(GLUface f) {
return !f.inside || f.marked;
}
@@ -226,8 +223,8 @@ class Render {
t.marked = false;
t = t.trail;
}
}
}
/* else absorb trailing semicolon */
}
@@ -254,7 +251,6 @@ class Render {
return newFace;
}
private static boolean IsEven(long n) {
return (n & 0x1L) == 0;
}
@@ -320,14 +316,13 @@ class Render {
}
}
static void RenderLonelyTriangles(GLUtessellatorImpl tess, GLUface f) {
/* Now we render all the separate triangles which could not be
* grouped into a triangle fan or strip.
*/
GLUhalfEdge e;
int newState;
int edgeState = -1; /* force edge state output for first vertex */
int edgeState = -1; /* force edge state output for first vertex */
tess.callBeginOrBeginData(GL_TRIANGLES);
@@ -343,10 +338,10 @@ class Render {
newState = (!e.Sym.Lface.inside) ? 1 : 0;
if (edgeState != newState) {
edgeState = newState;
tess.callEdgeFlagOrEdgeFlagData( edgeState != 0);
tess.callEdgeFlagOrEdgeFlagData(edgeState != 0);
}
}
tess.callVertexOrVertexData( e.Org.data);
tess.callVertexOrVertexData(e.Org.data);
e = e.Lnext;
} while (e != f.anEdge);
@@ -361,14 +356,14 @@ class Render {
* (otherwise we've goofed up somewhere).
*/
tess.callBeginOrBeginData(GL_TRIANGLE_FAN);
tess.callVertexOrVertexData( e.Org.data);
tess.callVertexOrVertexData( e.Sym.Org.data);
tess.callVertexOrVertexData(e.Org.data);
tess.callVertexOrVertexData(e.Sym.Org.data);
while (!Marked(e.Lface)) {
e.Lface.marked = true;
--size;
e = e.Onext;
tess.callVertexOrVertexData( e.Sym.Org.data);
tess.callVertexOrVertexData(e.Sym.Org.data);
}
assert (size == 0);
@@ -383,20 +378,20 @@ class Render {
* (otherwise we've goofed up somewhere).
*/
tess.callBeginOrBeginData(GL_TRIANGLE_STRIP);
tess.callVertexOrVertexData( e.Org.data);
tess.callVertexOrVertexData( e.Sym.Org.data);
tess.callVertexOrVertexData(e.Org.data);
tess.callVertexOrVertexData(e.Sym.Org.data);
while (!Marked(e.Lface)) {
e.Lface.marked = true;
--size;
e = e.Lnext.Sym;
tess.callVertexOrVertexData( e.Org.data);
tess.callVertexOrVertexData(e.Org.data);
if (Marked(e.Lface)) break;
e.Lface.marked = true;
--size;
e = e.Onext;
tess.callVertexOrVertexData( e.Sym.Org.data);
tess.callVertexOrVertexData(e.Sym.Org.data);
}
assert (size == 0);
@@ -406,10 +401,10 @@ class Render {
/************************ Boundary contour decomposition ******************/
/* __gl_renderBoundary( tess, mesh ) takes a mesh, and outputs one
* contour for each face marked "inside". The rendering output is
* provided as callbacks (see the api).
*/
/* __gl_renderBoundary( tess, mesh ) takes a mesh, and outputs one
* contour for each face marked "inside". The rendering output is
* provided as callbacks (see the api).
*/
public static void __gl_renderBoundary(GLUtessellatorImpl tess, GLUmesh mesh) {
GLUface f;
GLUhalfEdge e;
@@ -419,7 +414,7 @@ class Render {
tess.callBeginOrBeginData(GL_LINE_LOOP);
e = f.anEdge;
do {
tess.callVertexOrVertexData( e.Org.data);
tess.callVertexOrVertexData(e.Org.data);
e = e.Lnext;
} while (e != f.anEdge);
tess.callEndOrEndData();
@@ -427,13 +422,10 @@ class Render {
}
}
/************************ Quick-and-dirty decomposition ******************/
private static final int SIGN_INCONSISTENT = 2;
static int ComputeNormal(GLUtessellatorImpl tess, double[] norm, boolean check)
/*
static int ComputeNormal(GLUtessellatorImpl tess, double[] norm, boolean check) /*
* If check==false, we compute the polygon normal and place it in norm[].
* If check==true, we check that each triangle in the fan from v0 has a
* consistent orientation with respect to norm[]. If triangles are
@@ -442,9 +434,9 @@ class Render {
* SIGN_INCONSISTENT.
*/ {
CachedVertex[] v = tess.cache;
// CachedVertex vn = v0 + tess.cacheCount;
// CachedVertex vn = v0 + tess.cacheCount;
int vn = tess.cacheCount;
// CachedVertex vc;
// CachedVertex vc;
int vc;
double dot, xc, yc, zc, xp, yp, zp;
double[] n = new double[3];
@@ -512,18 +504,18 @@ class Render {
return sign;
}
/* __gl_renderCache( tess ) takes a single contour and tries to render it
* as a triangle fan. This handles convex polygons, as well as some
* non-convex polygons if we get lucky.
*
* Returns true if the polygon was successfully rendered. The rendering
* output is provided as callbacks (see the api).
*/
/* __gl_renderCache( tess ) takes a single contour and tries to render it
* as a triangle fan. This handles convex polygons, as well as some
* non-convex polygons if we get lucky.
*
* Returns true if the polygon was successfully rendered. The rendering
* output is provided as callbacks (see the api).
*/
public static boolean __gl_renderCache(GLUtessellatorImpl tess) {
CachedVertex[] v = tess.cache;
// CachedVertex vn = v0 + tess.cacheCount;
// CachedVertex vn = v0 + tess.cacheCount;
int vn = tess.cacheCount;
// CachedVertex vc;
// CachedVertex vc;
int vc;
double[] norm = new double[3];
int sign;
@@ -537,10 +529,10 @@ class Render {
norm[1] = tess.normal[1];
norm[2] = tess.normal[2];
if (norm[0] == 0 && norm[1] == 0 && norm[2] == 0) {
ComputeNormal( tess, norm, false);
ComputeNormal(tess, norm, false);
}
sign = ComputeNormal( tess, norm, true);
sign = ComputeNormal(tess, norm, true);
if (sign == SIGN_INCONSISTENT) {
/* Fan triangles did not have a consistent orientation */
return false;
@@ -550,7 +542,7 @@ class Render {
return true;
}
if ( !USE_OPTIMIZED_CODE_PATH ) {
if (!USE_OPTIMIZED_CODE_PATH) {
return false;
} else {
/* Make sure we do the right thing for each winding rule */
@@ -568,18 +560,17 @@ class Render {
return true;
}
tess.callBeginOrBeginData( tess.boundaryOnly ? GL_LINE_LOOP
: (tess.cacheCount > 3) ? GL_TRIANGLE_FAN
: GL_TRIANGLES);
tess.callBeginOrBeginData(
tess.boundaryOnly ? GL_LINE_LOOP : (tess.cacheCount > 3) ? GL_TRIANGLE_FAN : GL_TRIANGLES);
tess.callVertexOrVertexData( v[0].data);
tess.callVertexOrVertexData(v[0].data);
if (sign > 0) {
for (vc = 1; vc < vn; ++vc) {
tess.callVertexOrVertexData( v[vc].data);
tess.callVertexOrVertexData(v[vc].data);
}
} else {
for (vc = vn - 1; vc > 0; --vc) {
tess.callVertexOrVertexData( v[vc].data);
tess.callVertexOrVertexData(v[vc].data);
}
}
tess.callEndOrEndData();
@@ -31,112 +31,109 @@
*/
/*
* Portions Copyright (C) 2003-2006 Sun Microsystems, Inc.
* All rights reserved.
*/
* Portions Copyright (C) 2003-2006 Sun Microsystems, Inc.
* All rights reserved.
*/
/*
** License Applicability. Except to the extent portions of this file are
** made subject to an alternative license as permitted in the SGI Free
** Software License B, Version 1.1 (the "License"), the contents of this
** file are subject only to the provisions of the License. You may not use
** this file except in compliance with the License. You may obtain a copy
** of the License at Silicon Graphics, Inc., attn: Legal Services, 1600
** Amphitheatre Parkway, Mountain View, CA 94043-1351, or at:
**
** http://oss.sgi.com/projects/FreeB
**
** Note that, as provided in the License, the Software is distributed on an
** "AS IS" basis, with ALL EXPRESS AND IMPLIED WARRANTIES AND CONDITIONS
** DISCLAIMED, INCLUDING, WITHOUT LIMITATION, ANY IMPLIED WARRANTIES AND
** CONDITIONS OF MERCHANTABILITY, SATISFACTORY QUALITY, FITNESS FOR A
** PARTICULAR PURPOSE, AND NON-INFRINGEMENT.
**
** NOTE: The Original Code (as defined below) has been licensed to Sun
** Microsystems, Inc. ("Sun") under the SGI Free Software License B
** (Version 1.1), shown above ("SGI License"). Pursuant to Section
** 3.2(3) of the SGI License, Sun is distributing the Covered Code to
** you under an alternative license ("Alternative License"). This
** Alternative License includes all of the provisions of the SGI License
** except that Section 2.2 and 11 are omitted. Any differences between
** the Alternative License and the SGI License are offered solely by Sun
** and not by SGI.
**
** Original Code. The Original Code is: OpenGL Sample Implementation,
** Version 1.2.1, released January 26, 2000, developed by Silicon Graphics,
** Inc. The Original Code is Copyright (c) 1991-2000 Silicon Graphics, Inc.
** Copyright in any portions created by third parties is as indicated
** elsewhere herein. All Rights Reserved.
**
** Additional Notice Provisions: The application programming interfaces
** established by SGI in conjunction with the Original Code are The
** OpenGL(R) Graphics System: A Specification (Version 1.2.1), released
** April 1, 1999; The OpenGL(R) Graphics System Utility Library (Version
** 1.3), released November 4, 1998; and OpenGL(R) Graphics with the X
** Window System(R) (Version 1.3), released October 19, 1998. This software
** was created using the OpenGL(R) version 1.2.1 Sample Implementation
** published by SGI, but has not been independently verified as being
** compliant with the OpenGL(R) version 1.2.1 Specification.
**
** Author: Eric Veach, July 1994
** Java Port: Pepijn Van Eeckhoudt, July 2003
** Java Port: Nathan Parker Burg, August 2003
*/
** License Applicability. Except to the extent portions of this file are
** made subject to an alternative license as permitted in the SGI Free
** Software License B, Version 1.1 (the "License"), the contents of this
** file are subject only to the provisions of the License. You may not use
** this file except in compliance with the License. You may obtain a copy
** of the License at Silicon Graphics, Inc., attn: Legal Services, 1600
** Amphitheatre Parkway, Mountain View, CA 94043-1351, or at:
**
** http://oss.sgi.com/projects/FreeB
**
** Note that, as provided in the License, the Software is distributed on an
** "AS IS" basis, with ALL EXPRESS AND IMPLIED WARRANTIES AND CONDITIONS
** DISCLAIMED, INCLUDING, WITHOUT LIMITATION, ANY IMPLIED WARRANTIES AND
** CONDITIONS OF MERCHANTABILITY, SATISFACTORY QUALITY, FITNESS FOR A
** PARTICULAR PURPOSE, AND NON-INFRINGEMENT.
**
** NOTE: The Original Code (as defined below) has been licensed to Sun
** Microsystems, Inc. ("Sun") under the SGI Free Software License B
** (Version 1.1), shown above ("SGI License"). Pursuant to Section
** 3.2(3) of the SGI License, Sun is distributing the Covered Code to
** you under an alternative license ("Alternative License"). This
** Alternative License includes all of the provisions of the SGI License
** except that Section 2.2 and 11 are omitted. Any differences between
** the Alternative License and the SGI License are offered solely by Sun
** and not by SGI.
**
** Original Code. The Original Code is: OpenGL Sample Implementation,
** Version 1.2.1, released January 26, 2000, developed by Silicon Graphics,
** Inc. The Original Code is Copyright (c) 1991-2000 Silicon Graphics, Inc.
** Copyright in any portions created by third parties is as indicated
** elsewhere herein. All Rights Reserved.
**
** Additional Notice Provisions: The application programming interfaces
** established by SGI in conjunction with the Original Code are The
** OpenGL(R) Graphics System: A Specification (Version 1.2.1), released
** April 1, 1999; The OpenGL(R) Graphics System Utility Library (Version
** 1.3), released November 4, 1998; and OpenGL(R) Graphics with the X
** Window System(R) (Version 1.3), released October 19, 1998. This software
** was created using the OpenGL(R) version 1.2.1 Sample Implementation
** published by SGI, but has not been independently verified as being
** compliant with the OpenGL(R) version 1.2.1 Specification.
**
** Author: Eric Veach, July 1994
** Java Port: Pepijn Van Eeckhoudt, July 2003
** Java Port: Nathan Parker Burg, August 2003
*/
package org.lwjglx.util.glu.tessellation;
import static org.lwjglx.util.glu.GLU.*;
class Sweep {
private Sweep() {
}
private Sweep() {}
// #ifdef FOR_TRITE_TEST_PROGRAM
// extern void DebugEvent( GLUtessellator *tess );
// #else
private static void DebugEvent(GLUtessellatorImpl tess) {
// #ifdef FOR_TRITE_TEST_PROGRAM
// extern void DebugEvent( GLUtessellator *tess );
// #else
private static void DebugEvent(GLUtessellatorImpl tess) {}
}
// #endif
// #endif
/*
* Invariants for the Edge Dictionary.
* - each pair of adjacent edges e2=Succ(e1) satisfies EdgeLeq(e1,e2)
* at any valid location of the sweep event
* - if EdgeLeq(e2,e1) as well (at any valid sweep event), then e1 and e2
* share a common endpoint
* - for each e, e.Dst has been processed, but not e.Org
* - each edge e satisfies VertLeq(e.Dst,event) && VertLeq(event,e.Org)
* where "event" is the current sweep line event.
* - no edge e has zero length
*
* Invariants for the Mesh (the processed portion).
* - the portion of the mesh left of the sweep line is a planar graph,
* ie. there is *some* way to embed it in the plane
* - no processed edge has zero length
* - no two processed vertices have identical coordinates
* - each "inside" region is monotone, ie. can be broken into two chains
* of monotonically increasing vertices according to VertLeq(v1,v2)
* - a non-invariant: these chains may intersect (very slightly)
*
* Invariants for the Sweep.
* - if none of the edges incident to the event vertex have an activeRegion
* (ie. none of these edges are in the edge dictionary), then the vertex
* has only right-going edges.
* - if an edge is marked "fixUpperEdge" (it is a temporary edge introduced
* by ConnectRightVertex), then it is the only right-going edge from
* its associated vertex. (This says that these edges exist only
* when it is necessary.)
*/
/*
* Invariants for the Edge Dictionary.
* - each pair of adjacent edges e2=Succ(e1) satisfies EdgeLeq(e1,e2)
* at any valid location of the sweep event
* - if EdgeLeq(e2,e1) as well (at any valid sweep event), then e1 and e2
* share a common endpoint
* - for each e, e.Dst has been processed, but not e.Org
* - each edge e satisfies VertLeq(e.Dst,event) && VertLeq(event,e.Org)
* where "event" is the current sweep line event.
* - no edge e has zero length
*
* Invariants for the Mesh (the processed portion).
* - the portion of the mesh left of the sweep line is a planar graph,
* ie. there is *some* way to embed it in the plane
* - no processed edge has zero length
* - no two processed vertices have identical coordinates
* - each "inside" region is monotone, ie. can be broken into two chains
* of monotonically increasing vertices according to VertLeq(v1,v2)
* - a non-invariant: these chains may intersect (very slightly)
*
* Invariants for the Sweep.
* - if none of the edges incident to the event vertex have an activeRegion
* (ie. none of these edges are in the edge dictionary), then the vertex
* has only right-going edges.
* - if an edge is marked "fixUpperEdge" (it is a temporary edge introduced
* by ConnectRightVertex), then it is the only right-going edge from
* its associated vertex. (This says that these edges exist only
* when it is necessary.)
*/
/* When we merge two edges into one, we need to compute the combined
* winding of the new edge.
*/
/* When we merge two edges into one, we need to compute the combined
* winding of the new edge.
*/
private static void AddWinding(GLUhalfEdge eDst, GLUhalfEdge eSrc) {
eDst.winding += eSrc.winding;
eDst.Sym.winding += eSrc.Sym.winding;
}
private static ActiveRegion RegionBelow(ActiveRegion r) {
return ((ActiveRegion) Dict.dictKey(Dict.dictPred(r.nodeUp)));
}
@@ -145,8 +142,7 @@ class Sweep {
return ((ActiveRegion) Dict.dictKey(Dict.dictSucc(r.nodeUp)));
}
static boolean EdgeLeq(GLUtessellatorImpl tess, ActiveRegion reg1, ActiveRegion reg2)
/*
static boolean EdgeLeq(GLUtessellatorImpl tess, ActiveRegion reg1, ActiveRegion reg2) /*
* Both edges must be directed from right to left (this is the canonical
* direction for the upper edge of each region).
*
@@ -186,7 +182,6 @@ class Sweep {
return (t1 >= t2);
}
static void DeleteRegion(GLUtessellatorImpl tess, ActiveRegion reg) {
if (reg.fixUpperEdge) {
/* It was created with zero winding number, so it better be
@@ -199,9 +194,7 @@ class Sweep {
Dict.dictDelete(tess.dict, reg.nodeUp); /* __gl_dictListDelete */
}
static boolean FixUpperEdge(ActiveRegion reg, GLUhalfEdge newEdge)
/*
static boolean FixUpperEdge(ActiveRegion reg, GLUhalfEdge newEdge) /*
* Replace an upper edge which needs fixing (see ConnectRightVertex).
*/ {
assert (reg.fixUpperEdge);
@@ -244,17 +237,14 @@ class Sweep {
return reg;
}
static ActiveRegion AddRegionBelow(GLUtessellatorImpl tess,
ActiveRegion regAbove,
GLUhalfEdge eNewUp)
/*
static ActiveRegion AddRegionBelow(GLUtessellatorImpl tess, ActiveRegion regAbove, GLUhalfEdge eNewUp) /*
* Add a new active region to the sweep line, *somewhere* below "regAbove"
* (according to where the new edge belongs in the sweep-line dictionary).
* The upper edge of the new region will be "eNewUp".
* Winding number and "inside" flag are not updated.
*/ {
ActiveRegion regNew = new ActiveRegion();
//if (regNew == null) throw new RuntimeException();
// if (regNew == null) throw new RuntimeException();
regNew.eUp = eNewUp;
/* __gl_dictListInsertBefore */
@@ -282,20 +272,17 @@ class Sweep {
return (n >= 2) || (n <= -2);
}
/*LINTED*/
// assert (false);
// assert (false);
throw new InternalError();
/*NOTREACHED*/
}
static void ComputeWinding(GLUtessellatorImpl tess, ActiveRegion reg) {
reg.windingNumber = RegionAbove(reg).windingNumber + reg.eUp.winding;
reg.inside = IsWindingInside(tess, reg.windingNumber);
}
static void FinishRegion(GLUtessellatorImpl tess, ActiveRegion reg)
/*
static void FinishRegion(GLUtessellatorImpl tess, ActiveRegion reg) /*
* Delete a region from the sweep line. This happens when the upper
* and lower chains of a region meet (at a vertex on the sweep line).
* The "inside" flag is copied to the appropriate mesh face (we could
@@ -306,14 +293,11 @@ class Sweep {
GLUface f = e.Lface;
f.inside = reg.inside;
f.anEdge = e; /* optimization for __gl_meshTessellateMonoRegion() */
f.anEdge = e; /* optimization for __gl_meshTessellateMonoRegion() */
DeleteRegion(tess, reg);
}
static GLUhalfEdge FinishLeftRegions(GLUtessellatorImpl tess,
ActiveRegion regFirst, ActiveRegion regLast)
/*
static GLUhalfEdge FinishLeftRegions(GLUtessellatorImpl tess, ActiveRegion regFirst, ActiveRegion regLast) /*
* We are given a vertex with one or more left-going edges. All affected
* edges should be in the edge dictionary. Starting at regFirst.eUp,
* we walk down deleting all regions where both edges have the same
@@ -331,7 +315,7 @@ class Sweep {
regPrev = regFirst;
ePrev = regFirst.eUp;
while (regPrev != regLast) {
regPrev.fixUpperEdge = false; /* placement was OK */
regPrev.fixUpperEdge = false; /* placement was OK */
reg = RegionBelow(regPrev);
e = reg.eUp;
if (e.Org != ePrev.Org) {
@@ -358,27 +342,30 @@ class Sweep {
if (!Mesh.__gl_meshSplice(e.Sym.Lnext, e)) throw new RuntimeException();
if (!Mesh.__gl_meshSplice(ePrev, e)) throw new RuntimeException();
}
FinishRegion(tess, regPrev); /* may change reg.eUp */
FinishRegion(tess, regPrev); /* may change reg.eUp */
ePrev = reg.eUp;
regPrev = reg;
}
return ePrev;
}
static void AddRightEdges(GLUtessellatorImpl tess, ActiveRegion regUp,
GLUhalfEdge eFirst, GLUhalfEdge eLast, GLUhalfEdge eTopLeft,
boolean cleanUp)
/*
* Purpose: insert right-going edges into the edge dictionary, and update
* winding numbers and mesh connectivity appropriately. All right-going
* edges share a common origin vOrg. Edges are inserted CCW starting at
* eFirst; the last edge inserted is eLast.Sym.Lnext. If vOrg has any
* left-going edges already processed, then eTopLeft must be the edge
* such that an imaginary upward vertical segment from vOrg would be
* contained between eTopLeft.Sym.Lnext and eTopLeft; otherwise eTopLeft
* should be null.
*/ {
static void AddRightEdges(
GLUtessellatorImpl tess,
ActiveRegion regUp,
GLUhalfEdge eFirst,
GLUhalfEdge eLast,
GLUhalfEdge eTopLeft,
boolean cleanUp)
/*
* Purpose: insert right-going edges into the edge dictionary, and update
* winding numbers and mesh connectivity appropriately. All right-going
* edges share a common origin vOrg. Edges are inserted CCW starting at
* eFirst; the last edge inserted is eLast.Sym.Lnext. If vOrg has any
* left-going edges already processed, then eTopLeft must be the edge
* such that an imaginary upward vertical segment from vOrg would be
* contained between eTopLeft.Sym.Lnext and eTopLeft; otherwise eTopLeft
* should be null.
*/ {
ActiveRegion reg, regPrev;
GLUhalfEdge e, ePrev;
boolean firstTime = true;
@@ -400,7 +387,7 @@ class Sweep {
}
regPrev = regUp;
ePrev = eTopLeft;
for (; ;) {
for (; ; ) {
reg = RegionBelow(regPrev);
e = reg.eUp.Sym;
if (e.Org != ePrev.Org) break;
@@ -436,9 +423,7 @@ class Sweep {
}
}
static void CallCombine(GLUtessellatorImpl tess, GLUvertex isect,
Object[] data, float[] weights, boolean needed) {
static void CallCombine(GLUtessellatorImpl tess, GLUvertex isect, Object[] data, float[] weights, boolean needed) {
double[] coords = new double[3];
/* Copy coord data in case the callback changes it. */
@@ -463,14 +448,12 @@ class Sweep {
}
}
static void SpliceMergeVertices(GLUtessellatorImpl tess, GLUhalfEdge e1,
GLUhalfEdge e2)
/*
static void SpliceMergeVertices(GLUtessellatorImpl tess, GLUhalfEdge e1, GLUhalfEdge e2) /*
* Two vertices with idential coordinates are combined into one.
* e1.Org is kept, while e2.Org is discarded.
*/ {
Object[] data = new Object[4];
float[] weights = new float[]{0.5f, 0.5f, 0.0f, 0.0f};
float[] weights = new float[] {0.5f, 0.5f, 0.0f, 0.0f};
data[0] = e1.Org.data;
data[1] = e2.Org.data;
@@ -478,9 +461,7 @@ class Sweep {
if (!Mesh.__gl_meshSplice(e1, e2)) throw new RuntimeException();
}
static void VertexWeights(GLUvertex isect, GLUvertex org, GLUvertex dst,
float[] weights)
/*
static void VertexWeights(GLUvertex isect, GLUvertex org, GLUvertex dst, float[] weights) /*
* Find some weights which describe how the intersection vertex is
* a linear combination of "org" and "dest". Each of the two edges
* which generated "isect" is allocated 50% of the weight; each edge
@@ -497,15 +478,18 @@ class Sweep {
isect.coords[2] += weights[0] * org.coords[2] + weights[1] * dst.coords[2];
}
static void GetIntersectData(GLUtessellatorImpl tess, GLUvertex isect,
GLUvertex orgUp, GLUvertex dstUp,
GLUvertex orgLo, GLUvertex dstLo)
/*
* We've computed a new intersection point, now we need a "data" pointer
* from the user so that we can refer to this new vertex in the
* rendering callbacks.
*/ {
static void GetIntersectData(
GLUtessellatorImpl tess,
GLUvertex isect,
GLUvertex orgUp,
GLUvertex dstUp,
GLUvertex orgLo,
GLUvertex dstLo)
/*
* We've computed a new intersection point, now we need a "data" pointer
* from the user so that we can refer to this new vertex in the
* rendering callbacks.
*/ {
Object[] data = new Object[4];
float[] weights = new float[4];
float[] weights1 = new float[2];
@@ -525,8 +509,7 @@ class Sweep {
CallCombine(tess, isect, data, weights, true);
}
static boolean CheckForRightSplice(GLUtessellatorImpl tess, ActiveRegion regUp)
/*
static boolean CheckForRightSplice(GLUtessellatorImpl tess, ActiveRegion regUp) /*
* Check the upper and lower edge of "regUp", to make sure that the
* eUp.Org is above eLo, or eLo.Org is below eUp (depending on which
* origin is leftmost).
@@ -581,8 +564,7 @@ class Sweep {
return true;
}
static boolean CheckForLeftSplice(GLUtessellatorImpl tess, ActiveRegion regUp)
/*
static boolean CheckForLeftSplice(GLUtessellatorImpl tess, ActiveRegion regUp) /*
* Check the upper and lower edge of "regUp", to make sure that the
* eUp.Sym.Org is above eLo, or eLo.Sym.Org is below eUp (depending on which
* destination is rightmost).
@@ -629,9 +611,7 @@ class Sweep {
return true;
}
static boolean CheckForIntersect(GLUtessellatorImpl tess, ActiveRegion regUp)
/*
static boolean CheckForIntersect(GLUtessellatorImpl tess, ActiveRegion regUp) /*
* Check the upper and lower edges of the given region to see if
* they intersect. If so, create the intersection and add it
* to the data structures.
@@ -658,11 +638,11 @@ class Sweep {
assert (orgUp != tess.event && orgLo != tess.event);
assert (!regUp.fixUpperEdge && !regLo.fixUpperEdge);
if (orgUp == orgLo) return false; /* right endpoints are the same */
if (orgUp == orgLo) return false; /* right endpoints are the same */
tMinUp = Math.min(orgUp.t, dstUp.t);
tMaxLo = Math.max(orgLo.t, dstLo.t);
if (tMinUp > tMaxLo) return false; /* t ranges do not overlap */
if (tMinUp > tMaxLo) return false; /* t ranges do not overlap */
if (Geom.VertLeq(orgUp, orgLo)) {
if (Geom.EdgeSign(dstLo, orgUp, orgLo) > 0) return false;
@@ -708,10 +688,8 @@ class Sweep {
return false;
}
if ((!Geom.VertEq(dstUp, tess.event)
&& Geom.EdgeSign(dstUp, tess.event, isect) >= 0)
|| (!Geom.VertEq(dstLo, tess.event)
&& Geom.EdgeSign(dstLo, tess.event, isect) <= 0)) {
if ((!Geom.VertEq(dstUp, tess.event) && Geom.EdgeSign(dstUp, tess.event, isect) >= 0)
|| (!Geom.VertEq(dstLo, tess.event) && Geom.EdgeSign(dstLo, tess.event, isect) <= 0)) {
/* Very unusual -- the new upper or lower edge would pass on the
* wrong side of the sweep event, or through it. This can happen
* due to very small numerical errors in the intersection calculation.
@@ -774,7 +752,7 @@ class Sweep {
eUp.Org.t = isect.t;
eUp.Org.pqHandle = tess.pq.pqInsert(eUp.Org); /* __gl_pqSortInsert */
if (eUp.Org.pqHandle == Long.MAX_VALUE) {
tess.pq.pqDeletePriorityQ(); /* __gl_pqSortDeletePriorityQ */
tess.pq.pqDeletePriorityQ(); /* __gl_pqSortDeletePriorityQ */
tess.pq = null;
throw new RuntimeException();
}
@@ -783,8 +761,7 @@ class Sweep {
return false;
}
static void WalkDirtyRegions(GLUtessellatorImpl tess, ActiveRegion regUp)
/*
static void WalkDirtyRegions(GLUtessellatorImpl tess, ActiveRegion regUp) /*
* When the upper or lower edge of any region changes, the region is
* marked "dirty". This routine walks through all the dirty regions
* and makes sure that the dictionary invariants are satisfied
@@ -795,7 +772,7 @@ class Sweep {
ActiveRegion regLo = RegionBelow(regUp);
GLUhalfEdge eUp, eLo;
for (; ;) {
for (; ; ) {
/* Find the lowest dirty region (we walk from the bottom up). */
while (regLo.dirty) {
regUp = regLo;
@@ -836,7 +813,8 @@ class Sweep {
}
if (eUp.Org != eLo.Org) {
if (eUp.Sym.Org != eLo.Sym.Org
&& !regUp.fixUpperEdge && !regLo.fixUpperEdge
&& !regUp.fixUpperEdge
&& !regLo.fixUpperEdge
&& (eUp.Sym.Org == tess.event || eLo.Sym.Org == tess.event)) {
/* When all else fails in CheckForIntersect(), it uses tess.event
* as the intersection location. To make this possible, it requires
@@ -845,7 +823,7 @@ class Sweep {
* case it might splice one of these edges into tess.event, and
* violate the invariant that fixable edges are the only right-going
* edge from their associated vertex).
*/
*/
if (CheckForIntersect(tess, regUp)) {
/* WalkDirtyRegions() was called recursively; we're done */
return;
@@ -867,10 +845,7 @@ class Sweep {
}
}
static void ConnectRightVertex(GLUtessellatorImpl tess, ActiveRegion regUp,
GLUhalfEdge eBottomLeft)
/*
static void ConnectRightVertex(GLUtessellatorImpl tess, ActiveRegion regUp, GLUhalfEdge eBottomLeft) /*
* Purpose: connect a "right" vertex vEvent (one where all edges go left)
* to the unprocessed portion of the mesh. Since there are no right-going
* edges, two regions (one above vEvent and one below) are being merged
@@ -952,18 +927,16 @@ class Sweep {
WalkDirtyRegions(tess, regUp);
}
/* Because vertices at exactly the same location are merged together
* before we process the sweep event, some degenerate cases can't occur.
* However if someone eventually makes the modifications required to
* merge features which are close together, the cases below marked
* TOLERANCE_NONZERO will be useful. They were debugged before the
* code to merge identical vertices in the main loop was added.
*/
/* Because vertices at exactly the same location are merged together
* before we process the sweep event, some degenerate cases can't occur.
* However if someone eventually makes the modifications required to
* merge features which are close together, the cases below marked
* TOLERANCE_NONZERO will be useful. They were debugged before the
* code to merge identical vertices in the main loop was added.
*/
private static final boolean TOLERANCE_NONZERO = false;
static void ConnectLeftDegenerate(GLUtessellatorImpl tess,
ActiveRegion regUp, GLUvertex vEvent)
/*
static void ConnectLeftDegenerate(GLUtessellatorImpl tess, ActiveRegion regUp, GLUvertex vEvent) /*
* The event vertex lies exacty on an already-processed edge or vertex.
* Adding the new vertex involves splicing it into the already-processed
* part of the mesh.
@@ -990,7 +963,7 @@ class Sweep {
regUp.fixUpperEdge = false;
}
if (!Mesh.__gl_meshSplice(vEvent.anEdge, e)) throw new RuntimeException();
SweepEvent(tess, vEvent); /* recurse */
SweepEvent(tess, vEvent); /* recurse */
return;
}
@@ -1006,7 +979,7 @@ class Sweep {
/* Here e.Sym.Org has only a single fixable edge going right.
* We can delete it since now we have some real right-going edges.
*/
assert (eTopLeft != eTopRight); /* there are some left edges too */
assert (eTopLeft != eTopRight); /* there are some left edges too */
DeleteRegion(tess, reg);
if (!Mesh.__gl_meshDelete(eTopRight)) throw new RuntimeException();
eTopRight = eTopLeft.Sym.Lnext;
@@ -1019,9 +992,7 @@ class Sweep {
AddRightEdges(tess, regUp, eTopRight.Onext, eLast, eTopLeft, true);
}
static void ConnectLeftVertex(GLUtessellatorImpl tess, GLUvertex vEvent)
/*
static void ConnectLeftVertex(GLUtessellatorImpl tess, GLUvertex vEvent) /*
* Purpose: connect a "left" vertex (one where both edges go right)
* to the processed portion of the mesh. Let R be the active region
* containing vEvent, and let U and L be the upper and lower edge
@@ -1044,7 +1015,8 @@ class Sweep {
/* Get a pointer to the active region containing vEvent */
tmp.eUp = vEvent.anEdge.Sym;
/* __GL_DICTLISTKEY */ /* __gl_dictListSearch */
/* __GL_DICTLISTKEY */
/* __gl_dictListSearch */
regUp = (ActiveRegion) Dict.dictKey(Dict.dictSearch(tess.dict, tmp));
regLo = RegionBelow(regUp);
eUp = regUp.eUp;
@@ -1085,16 +1057,14 @@ class Sweep {
}
}
static void SweepEvent(GLUtessellatorImpl tess, GLUvertex vEvent)
/*
static void SweepEvent(GLUtessellatorImpl tess, GLUvertex vEvent) /*
* Does everything necessary when the sweep line crosses a vertex.
* Updates the mesh and the edge dictionary.
*/ {
ActiveRegion regUp, reg;
GLUhalfEdge e, eTopLeft, eBottomLeft;
tess.event = vEvent; /* for access in EdgeLeq() */
tess.event = vEvent; /* for access in EdgeLeq() */
DebugEvent(tess);
/* Check if this vertex is the right endpoint of an edge that is
@@ -1137,22 +1107,20 @@ class Sweep {
}
}
/* Make the sentinel coordinates big enough that they will never be
* merged with real input features. (Even with the largest possible
* input contour and the maximum tolerance of 1.0, no merging will be
* done with coordinates larger than 3 * GLU_TESS_MAX_COORD).
*/
/* Make the sentinel coordinates big enough that they will never be
* merged with real input features. (Even with the largest possible
* input contour and the maximum tolerance of 1.0, no merging will be
* done with coordinates larger than 3 * GLU_TESS_MAX_COORD).
*/
private static final double SENTINEL_COORD = (4.0 * GLU_TESS_MAX_COORD);
static void AddSentinel(GLUtessellatorImpl tess, double t)
/*
static void AddSentinel(GLUtessellatorImpl tess, double t) /*
* We add two sentinel edges above and below all other edges,
* to avoid special cases at the top and bottom.
*/ {
GLUhalfEdge e;
ActiveRegion reg = new ActiveRegion();
//if (reg == null) throw new RuntimeException();
// if (reg == null) throw new RuntimeException();
e = Mesh.__gl_meshMakeEdge(tess.mesh);
if (e == null) throw new RuntimeException();
@@ -1161,7 +1129,7 @@ class Sweep {
e.Org.t = t;
e.Sym.Org.s = -SENTINEL_COORD;
e.Sym.Org.t = t;
tess.event = e.Sym.Org; /* initialize it */
tess.event = e.Sym.Org; /* initialize it */
reg.eUp = e;
reg.windingNumber = 0;
@@ -1173,9 +1141,7 @@ class Sweep {
if (reg.nodeUp == null) throw new RuntimeException();
}
static void InitEdgeDict(final GLUtessellatorImpl tess)
/*
static void InitEdgeDict(final GLUtessellatorImpl tess) /*
* We maintain an ordering of edge intersections with the sweep line.
* This order is maintained in a dynamic dictionary.
*/ {
@@ -1191,12 +1157,12 @@ class Sweep {
AddSentinel(tess, SENTINEL_COORD);
}
static void DoneEdgeDict(GLUtessellatorImpl tess) {
ActiveRegion reg;
int fixedEdges = 0;
/* __GL_DICTLISTKEY */ /* __GL_DICTLISTMIN */
/* __GL_DICTLISTKEY */
/* __GL_DICTLISTMIN */
while ((reg = (ActiveRegion) Dict.dictKey(Dict.dictMin(tess.dict))) != null) {
/*
* At the end of all processing, the dictionary should contain
@@ -1209,14 +1175,12 @@ class Sweep {
}
assert (reg.windingNumber == 0);
DeleteRegion(tess, reg);
/* __gl_meshDelete( reg.eUp );*/
/* __gl_meshDelete( reg.eUp );*/
}
Dict.dictDeleteDict(tess.dict); /* __gl_dictListDeleteDict */
Dict.dictDeleteDict(tess.dict); /* __gl_dictListDeleteDict */
}
static void RemoveDegenerateEdges(GLUtessellatorImpl tess)
/*
static void RemoveDegenerateEdges(GLUtessellatorImpl tess) /*
* Remove zero-length edges, and contours with fewer than 3 vertices.
*/ {
GLUhalfEdge e, eNext, eLnext;
@@ -1230,7 +1194,7 @@ class Sweep {
if (Geom.VertEq(e.Org, e.Sym.Org) && e.Lnext.Lnext != e) {
/* Zero-length edge, contour has at least 3 edges */
SpliceMergeVertices(tess, eLnext, e); /* deletes e.Org */
SpliceMergeVertices(tess, eLnext, e); /* deletes e.Org */
if (!Mesh.__gl_meshDelete(e)) throw new RuntimeException(); /* e is a self-loop */
e = eLnext;
eLnext = e.Lnext;
@@ -1252,8 +1216,7 @@ class Sweep {
}
}
static boolean InitPriorityQ(GLUtessellatorImpl tess)
/*
static boolean InitPriorityQ(GLUtessellatorImpl tess) /*
* Insert all vertices into the priority queue which determines the
* order in which vertices cross the sweep line.
*/ {
@@ -1273,8 +1236,9 @@ class Sweep {
v.pqHandle = pq.pqInsert(v); /* __gl_pqSortInsert */
if (v.pqHandle == Long.MAX_VALUE) break;
}
if (v != vHead || !pq.pqInit()) { /* __gl_pqSortInit */
tess.pq.pqDeletePriorityQ(); /* __gl_pqSortDeletePriorityQ */
if (v != vHead || !pq.pqInit()) {
/* __gl_pqSortInit */
tess.pq.pqDeletePriorityQ(); /* __gl_pqSortDeletePriorityQ */
tess.pq = null;
return false;
}
@@ -1282,14 +1246,11 @@ class Sweep {
return true;
}
static void DonePriorityQ(GLUtessellatorImpl tess) {
tess.pq.pqDeletePriorityQ(); /* __gl_pqSortDeletePriorityQ */
}
static boolean RemoveDegenerateFaces(GLUmesh mesh)
/*
static boolean RemoveDegenerateFaces(GLUmesh mesh) /*
* Delete any degenerate faces with only two edges. WalkDirtyRegions()
* will catch almost all of these, but it won't catch degenerate faces
* produced by splice operations on already-processed edges.
@@ -1321,8 +1282,7 @@ class Sweep {
return true;
}
public static boolean __gl_computeInterior(GLUtessellatorImpl tess)
/*
public static boolean __gl_computeInterior(GLUtessellatorImpl tess) /*
* __gl_computeInterior( tess ) computes the planar arrangement specified
* by the given contours, and further subdivides this arrangement
* into regions. Each region is marked "inside" if it belongs
@@ -1345,7 +1305,7 @@ class Sweep {
/* __gl_pqSortExtractMin */
while ((v = (GLUvertex) tess.pq.pqExtractMin()) != null) {
for (; ;) {
for (; ; ) {
vNext = (GLUvertex) tess.pq.pqMinimum(); /* __gl_pqSortMinimum */
if (vNext == null || !Geom.VertEq(vNext, v)) break;
@@ -1370,7 +1330,8 @@ class Sweep {
}
/* Set tess.event for debugging purposes */
/* __GL_DICTLISTKEY */ /* __GL_DICTLISTMIN */
/* __GL_DICTLISTKEY */
/* __GL_DICTLISTMIN */
tess.event = ((ActiveRegion) Dict.dictKey(Dict.dictMin(tess.dict))).eUp.Org;
DebugEvent(tess);
DoneEdgeDict(tess);
@@ -31,87 +31,87 @@
*/
/*
* Portions Copyright (C) 2003-2006 Sun Microsystems, Inc.
* All rights reserved.
*/
* Portions Copyright (C) 2003-2006 Sun Microsystems, Inc.
* All rights reserved.
*/
/*
** License Applicability. Except to the extent portions of this file are
** made subject to an alternative license as permitted in the SGI Free
** Software License B, Version 1.1 (the "License"), the contents of this
** file are subject only to the provisions of the License. You may not use
** this file except in compliance with the License. You may obtain a copy
** of the License at Silicon Graphics, Inc., attn: Legal Services, 1600
** Amphitheatre Parkway, Mountain View, CA 94043-1351, or at:
**
** http://oss.sgi.com/projects/FreeB
**
** Note that, as provided in the License, the Software is distributed on an
** "AS IS" basis, with ALL EXPRESS AND IMPLIED WARRANTIES AND CONDITIONS
** DISCLAIMED, INCLUDING, WITHOUT LIMITATION, ANY IMPLIED WARRANTIES AND
** CONDITIONS OF MERCHANTABILITY, SATISFACTORY QUALITY, FITNESS FOR A
** PARTICULAR PURPOSE, AND NON-INFRINGEMENT.
**
** NOTE: The Original Code (as defined below) has been licensed to Sun
** Microsystems, Inc. ("Sun") under the SGI Free Software License B
** (Version 1.1), shown above ("SGI License"). Pursuant to Section
** 3.2(3) of the SGI License, Sun is distributing the Covered Code to
** you under an alternative license ("Alternative License"). This
** Alternative License includes all of the provisions of the SGI License
** except that Section 2.2 and 11 are omitted. Any differences between
** the Alternative License and the SGI License are offered solely by Sun
** and not by SGI.
**
** Original Code. The Original Code is: OpenGL Sample Implementation,
** Version 1.2.1, released January 26, 2000, developed by Silicon Graphics,
** Inc. The Original Code is Copyright (c) 1991-2000 Silicon Graphics, Inc.
** Copyright in any portions created by third parties is as indicated
** elsewhere herein. All Rights Reserved.
**
** Additional Notice Provisions: The application programming interfaces
** established by SGI in conjunction with the Original Code are The
** OpenGL(R) Graphics System: A Specification (Version 1.2.1), released
** April 1, 1999; The OpenGL(R) Graphics System Utility Library (Version
** 1.3), released November 4, 1998; and OpenGL(R) Graphics with the X
** Window System(R) (Version 1.3), released October 19, 1998. This software
** was created using the OpenGL(R) version 1.2.1 Sample Implementation
** published by SGI, but has not been independently verified as being
** compliant with the OpenGL(R) version 1.2.1 Specification.
**
** Author: Eric Veach, July 1994
** Java Port: Pepijn Van Eeckhoudt, July 2003
** Java Port: Nathan Parker Burg, August 2003
*/
** License Applicability. Except to the extent portions of this file are
** made subject to an alternative license as permitted in the SGI Free
** Software License B, Version 1.1 (the "License"), the contents of this
** file are subject only to the provisions of the License. You may not use
** this file except in compliance with the License. You may obtain a copy
** of the License at Silicon Graphics, Inc., attn: Legal Services, 1600
** Amphitheatre Parkway, Mountain View, CA 94043-1351, or at:
**
** http://oss.sgi.com/projects/FreeB
**
** Note that, as provided in the License, the Software is distributed on an
** "AS IS" basis, with ALL EXPRESS AND IMPLIED WARRANTIES AND CONDITIONS
** DISCLAIMED, INCLUDING, WITHOUT LIMITATION, ANY IMPLIED WARRANTIES AND
** CONDITIONS OF MERCHANTABILITY, SATISFACTORY QUALITY, FITNESS FOR A
** PARTICULAR PURPOSE, AND NON-INFRINGEMENT.
**
** NOTE: The Original Code (as defined below) has been licensed to Sun
** Microsystems, Inc. ("Sun") under the SGI Free Software License B
** (Version 1.1), shown above ("SGI License"). Pursuant to Section
** 3.2(3) of the SGI License, Sun is distributing the Covered Code to
** you under an alternative license ("Alternative License"). This
** Alternative License includes all of the provisions of the SGI License
** except that Section 2.2 and 11 are omitted. Any differences between
** the Alternative License and the SGI License are offered solely by Sun
** and not by SGI.
**
** Original Code. The Original Code is: OpenGL Sample Implementation,
** Version 1.2.1, released January 26, 2000, developed by Silicon Graphics,
** Inc. The Original Code is Copyright (c) 1991-2000 Silicon Graphics, Inc.
** Copyright in any portions created by third parties is as indicated
** elsewhere herein. All Rights Reserved.
**
** Additional Notice Provisions: The application programming interfaces
** established by SGI in conjunction with the Original Code are The
** OpenGL(R) Graphics System: A Specification (Version 1.2.1), released
** April 1, 1999; The OpenGL(R) Graphics System Utility Library (Version
** 1.3), released November 4, 1998; and OpenGL(R) Graphics with the X
** Window System(R) (Version 1.3), released October 19, 1998. This software
** was created using the OpenGL(R) version 1.2.1 Sample Implementation
** published by SGI, but has not been independently verified as being
** compliant with the OpenGL(R) version 1.2.1 Specification.
**
** Author: Eric Veach, July 1994
** Java Port: Pepijn Van Eeckhoudt, July 2003
** Java Port: Nathan Parker Burg, August 2003
*/
package org.lwjglx.util.glu.tessellation;
class TessMono {
/* __gl_meshTessellateMonoRegion( face ) tessellates a monotone region
* (what else would it do??) The region must consist of a single
* loop of half-edges (see mesh.h) oriented CCW. "Monotone" in this
* case means that any vertical line intersects the interior of the
* region in a single interval.
*
* Tessellation consists of adding interior edges (actually pairs of
* half-edges), to split the region into non-overlapping triangles.
*
* The basic idea is explained in Preparata and Shamos (which I don''t
* have handy right now), although their implementation is more
* complicated than this one. The are two edge chains, an upper chain
* and a lower chain. We process all vertices from both chains in order,
* from right to left.
*
* The algorithm ensures that the following invariant holds after each
* vertex is processed: the untessellated region consists of two
* chains, where one chain (say the upper) is a single edge, and
* the other chain is concave. The left vertex of the single edge
* is always to the left of all vertices in the concave chain.
*
* Each step consists of adding the rightmost unprocessed vertex to one
* of the two chains, and forming a fan of triangles from the rightmost
* of two chain endpoints. Determining whether we can add each triangle
* to the fan is a simple orientation test. By making the fan as large
* as possible, we restore the invariant (check it yourself).
*/
/* __gl_meshTessellateMonoRegion( face ) tessellates a monotone region
* (what else would it do??) The region must consist of a single
* loop of half-edges (see mesh.h) oriented CCW. "Monotone" in this
* case means that any vertical line intersects the interior of the
* region in a single interval.
*
* Tessellation consists of adding interior edges (actually pairs of
* half-edges), to split the region into non-overlapping triangles.
*
* The basic idea is explained in Preparata and Shamos (which I don''t
* have handy right now), although their implementation is more
* complicated than this one. The are two edge chains, an upper chain
* and a lower chain. We process all vertices from both chains in order,
* from right to left.
*
* The algorithm ensures that the following invariant holds after each
* vertex is processed: the untessellated region consists of two
* chains, where one chain (say the upper) is a single edge, and
* the other chain is concave. The left vertex of the single edge
* is always to the left of all vertices in the concave chain.
*
* Each step consists of adding the rightmost unprocessed vertex to one
* of the two chains, and forming a fan of triangles from the rightmost
* of two chain endpoints. Determining whether we can add each triangle
* to the fan is a simple orientation test. By making the fan as large
* as possible, we restore the invariant (check it yourself).
*/
static boolean __gl_meshTessellateMonoRegion(GLUface face) {
GLUhalfEdge up, lo;
@@ -135,8 +135,8 @@ class TessMono {
* The EdgeGoesLeft test guarantees progress even when some triangles
* are CW, given that the upper and lower chains are truly monotone.
*/
while (lo.Lnext != up && (Geom.EdgeGoesLeft(lo.Lnext)
|| Geom.EdgeSign(lo.Org, lo.Sym.Org, lo.Lnext.Sym.Org) <= 0)) {
while (lo.Lnext != up
&& (Geom.EdgeGoesLeft(lo.Lnext) || Geom.EdgeSign(lo.Org, lo.Sym.Org, lo.Lnext.Sym.Org) <= 0)) {
GLUhalfEdge tempHalfEdge = Mesh.__gl_meshConnect(lo.Lnext, lo);
if (tempHalfEdge == null) return false;
lo = tempHalfEdge.Sym;
@@ -144,8 +144,9 @@ class TessMono {
lo = lo.Onext.Sym;
} else {
/* lo.Org is on the left. We can make CCW triangles from up.Sym.Org. */
while (lo.Lnext != up && (Geom.EdgeGoesRight(up.Onext.Sym)
|| Geom.EdgeSign(up.Sym.Org, up.Org, up.Onext.Sym.Org) >= 0)) {
while (lo.Lnext != up
&& (Geom.EdgeGoesRight(up.Onext.Sym)
|| Geom.EdgeSign(up.Sym.Org, up.Org, up.Onext.Sym.Org) >= 0)) {
GLUhalfEdge tempHalfEdge = Mesh.__gl_meshConnect(up, up.Onext.Sym);
if (tempHalfEdge == null) return false;
up = tempHalfEdge.Sym;
@@ -167,11 +168,10 @@ class TessMono {
return true;
}
/* __gl_meshTessellateInterior( mesh ) tessellates each region of
* the mesh which is marked "inside" the polygon. Each such region
* must be monotone.
*/
/* __gl_meshTessellateInterior( mesh ) tessellates each region of
* the mesh which is marked "inside" the polygon. Each such region
* must be monotone.
*/
public static boolean __gl_meshTessellateInterior(GLUmesh mesh) {
GLUface f, next;
@@ -187,12 +187,11 @@ class TessMono {
return true;
}
/* __gl_meshDiscardExterior( mesh ) zaps (ie. sets to NULL) all faces
* which are not marked "inside" the polygon. Since further mesh operations
* on NULL faces are not allowed, the main purpose is to clean up the
* mesh so that exterior loops are not represented in the data structure.
*/
/* __gl_meshDiscardExterior( mesh ) zaps (ie. sets to NULL) all faces
* which are not marked "inside" the polygon. Since further mesh operations
* on NULL faces are not allowed, the main purpose is to clean up the
* mesh so that exterior loops are not represented in the data structure.
*/
public static void __gl_meshDiscardExterior(GLUmesh mesh) {
GLUface f, next;
@@ -206,16 +205,16 @@ class TessMono {
}
}
// private static final int MARKED_FOR_DELETION = 0x7fffffff;
// private static final int MARKED_FOR_DELETION = 0x7fffffff;
/* __gl_meshSetWindingNumber( mesh, value, keepOnlyBoundary ) resets the
* winding numbers on all edges so that regions marked "inside" the
* polygon have a winding number of "value", and regions outside
* have a winding number of 0.
*
* If keepOnlyBoundary is TRUE, it also deletes all edges which do not
* separate an interior region from an exterior one.
*/
/* __gl_meshSetWindingNumber( mesh, value, keepOnlyBoundary ) resets the
* winding numbers on all edges so that regions marked "inside" the
* polygon have a winding number of "value", and regions outside
* have a winding number of 0.
*
* If keepOnlyBoundary is TRUE, it also deletes all edges which do not
* separate an interior region from an exterior one.
*/
public static boolean __gl_meshSetWindingNumber(GLUmesh mesh, int value, boolean keepOnlyBoundary) {
GLUhalfEdge e, eNext;
@@ -237,5 +236,4 @@ class TessMono {
}
return true;
}
}
@@ -31,57 +31,57 @@
*/
/*
* Portions Copyright (C) 2003-2006 Sun Microsystems, Inc.
* All rights reserved.
*/
* Portions Copyright (C) 2003-2006 Sun Microsystems, Inc.
* All rights reserved.
*/
/*
** License Applicability. Except to the extent portions of this file are
** made subject to an alternative license as permitted in the SGI Free
** Software License B, Version 1.1 (the "License"), the contents of this
** file are subject only to the provisions of the License. You may not use
** this file except in compliance with the License. You may obtain a copy
** of the License at Silicon Graphics, Inc., attn: Legal Services, 1600
** Amphitheatre Parkway, Mountain View, CA 94043-1351, or at:
**
** http://oss.sgi.com/projects/FreeB
**
** Note that, as provided in the License, the Software is distributed on an
** "AS IS" basis, with ALL EXPRESS AND IMPLIED WARRANTIES AND CONDITIONS
** DISCLAIMED, INCLUDING, WITHOUT LIMITATION, ANY IMPLIED WARRANTIES AND
** CONDITIONS OF MERCHANTABILITY, SATISFACTORY QUALITY, FITNESS FOR A
** PARTICULAR PURPOSE, AND NON-INFRINGEMENT.
**
** NOTE: The Original Code (as defined below) has been licensed to Sun
** Microsystems, Inc. ("Sun") under the SGI Free Software License B
** (Version 1.1), shown above ("SGI License"). Pursuant to Section
** 3.2(3) of the SGI License, Sun is distributing the Covered Code to
** you under an alternative license ("Alternative License"). This
** Alternative License includes all of the provisions of the SGI License
** except that Section 2.2 and 11 are omitted. Any differences between
** the Alternative License and the SGI License are offered solely by Sun
** and not by SGI.
**
** Original Code. The Original Code is: OpenGL Sample Implementation,
** Version 1.2.1, released January 26, 2000, developed by Silicon Graphics,
** Inc. The Original Code is Copyright (c) 1991-2000 Silicon Graphics, Inc.
** Copyright in any portions created by third parties is as indicated
** elsewhere herein. All Rights Reserved.
**
** Additional Notice Provisions: The application programming interfaces
** established by SGI in conjunction with the Original Code are The
** OpenGL(R) Graphics System: A Specification (Version 1.2.1), released
** April 1, 1999; The OpenGL(R) Graphics System Utility Library (Version
** 1.3), released November 4, 1998; and OpenGL(R) Graphics with the X
** Window System(R) (Version 1.3), released October 19, 1998. This software
** was created using the OpenGL(R) version 1.2.1 Sample Implementation
** published by SGI, but has not been independently verified as being
** compliant with the OpenGL(R) version 1.2.1 Specification.
**
** Author: Eric Veach, July 1994
** Java Port: Pepijn Van Eeckhoudt, July 2003
** Java Port: Nathan Parker Burg, August 2003
*/
** License Applicability. Except to the extent portions of this file are
** made subject to an alternative license as permitted in the SGI Free
** Software License B, Version 1.1 (the "License"), the contents of this
** file are subject only to the provisions of the License. You may not use
** this file except in compliance with the License. You may obtain a copy
** of the License at Silicon Graphics, Inc., attn: Legal Services, 1600
** Amphitheatre Parkway, Mountain View, CA 94043-1351, or at:
**
** http://oss.sgi.com/projects/FreeB
**
** Note that, as provided in the License, the Software is distributed on an
** "AS IS" basis, with ALL EXPRESS AND IMPLIED WARRANTIES AND CONDITIONS
** DISCLAIMED, INCLUDING, WITHOUT LIMITATION, ANY IMPLIED WARRANTIES AND
** CONDITIONS OF MERCHANTABILITY, SATISFACTORY QUALITY, FITNESS FOR A
** PARTICULAR PURPOSE, AND NON-INFRINGEMENT.
**
** NOTE: The Original Code (as defined below) has been licensed to Sun
** Microsystems, Inc. ("Sun") under the SGI Free Software License B
** (Version 1.1), shown above ("SGI License"). Pursuant to Section
** 3.2(3) of the SGI License, Sun is distributing the Covered Code to
** you under an alternative license ("Alternative License"). This
** Alternative License includes all of the provisions of the SGI License
** except that Section 2.2 and 11 are omitted. Any differences between
** the Alternative License and the SGI License are offered solely by Sun
** and not by SGI.
**
** Original Code. The Original Code is: OpenGL Sample Implementation,
** Version 1.2.1, released January 26, 2000, developed by Silicon Graphics,
** Inc. The Original Code is Copyright (c) 1991-2000 Silicon Graphics, Inc.
** Copyright in any portions created by third parties is as indicated
** elsewhere herein. All Rights Reserved.
**
** Additional Notice Provisions: The application programming interfaces
** established by SGI in conjunction with the Original Code are The
** OpenGL(R) Graphics System: A Specification (Version 1.2.1), released
** April 1, 1999; The OpenGL(R) Graphics System Utility Library (Version
** 1.3), released November 4, 1998; and OpenGL(R) Graphics with the X
** Window System(R) (Version 1.3), released October 19, 1998. This software
** was created using the OpenGL(R) version 1.2.1 Sample Implementation
** published by SGI, but has not been independently verified as being
** compliant with the OpenGL(R) version 1.2.1 Specification.
**
** Author: Eric Veach, July 1994
** Java Port: Pepijn Van Eeckhoudt, July 2003
** Java Port: Nathan Parker Burg, August 2003
*/
package org.lwjglx.util.glu.tessellation;
class TessState {
@@ -45,90 +45,79 @@ import java.nio.FloatBuffer;
*/
public abstract class Matrix implements Serializable {
/**
* Constructor for Matrix.
*/
protected Matrix() {
super();
}
/**
* Constructor for Matrix.
*/
protected Matrix() {
super();
}
/**
* Set this matrix to be the identity matrix.
* @return this
*/
public abstract Matrix setIdentity();
/**
* Set this matrix to be the identity matrix.
* @return this
*/
public abstract Matrix setIdentity();
/**
* Invert this matrix
* @return this
*/
public abstract Matrix invert();
/**
* Invert this matrix
* @return this
*/
public abstract Matrix invert();
/**
* Load from a float buffer. The buffer stores the matrix in column major
* (OpenGL) order.
*
* @param buf A float buffer to read from
* @return this
*/
public abstract Matrix load(FloatBuffer buf);
/**
* Load from a float buffer. The buffer stores the matrix in row major
* (mathematical) order.
*
* @param buf A float buffer to read from
* @return this
*/
public abstract Matrix loadTranspose(FloatBuffer buf);
/**
* Load from a float buffer. The buffer stores the matrix in column major
* (OpenGL) order.
*
* @param buf A float buffer to read from
* @return this
*/
public abstract Matrix load(FloatBuffer buf);
/**
* Negate this matrix
* @return this
*/
public abstract Matrix negate();
/**
* Store this matrix in a float buffer. The matrix is stored in column
* major (openGL) order.
* @param buf The buffer to store this matrix in
* @return this
*/
public abstract Matrix store(FloatBuffer buf);
/**
* Load from a float buffer. The buffer stores the matrix in row major
* (mathematical) order.
*
* @param buf A float buffer to read from
* @return this
*/
public abstract Matrix loadTranspose(FloatBuffer buf);
/**
* Store this matrix in a float buffer. The matrix is stored in row
* major (maths) order.
* @param buf The buffer to store this matrix in
* @return this
*/
public abstract Matrix storeTranspose(FloatBuffer buf);
/**
* Transpose this matrix
* @return this
*/
public abstract Matrix transpose();
/**
* Negate this matrix
* @return this
*/
public abstract Matrix negate();
/**
* Store this matrix in a float buffer. The matrix is stored in column
* major (openGL) order.
* @param buf The buffer to store this matrix in
* @return this
*/
public abstract Matrix store(FloatBuffer buf);
/**
* Store this matrix in a float buffer. The matrix is stored in row
* major (maths) order.
* @param buf The buffer to store this matrix in
* @return this
*/
public abstract Matrix storeTranspose(FloatBuffer buf);
/**
* Transpose this matrix
* @return this
*/
public abstract Matrix transpose();
/**
* Set this matrix to 0.
* @return this
*/
public abstract Matrix setZero();
/**
* @return the determinant of the matrix
*/
public abstract float determinant();
/**
* Set this matrix to 0.
* @return this
*/
public abstract Matrix setZero();
/**
* @return the determinant of the matrix
*/
public abstract float determinant();
}
+291 -303
View File
@@ -42,359 +42,347 @@ import java.nio.FloatBuffer;
* @version $Revision: 3799 $
* $Id: Matrix2f.java 3799 2012-09-12 11:29:40Z kappa1 $
*/
public class Matrix2f extends Matrix implements Serializable {
private static final long serialVersionUID = 1L;
private static final long serialVersionUID = 1L;
public float m00, m01, m10, m11;
public float m00, m01, m10, m11;
/**
* Constructor for Matrix2f. The matrix is initialised to the identity.
*/
public Matrix2f() {
setIdentity();
}
/**
* Constructor for Matrix2f. The matrix is initialised to the identity.
*/
public Matrix2f() {
setIdentity();
}
/**
* Constructor
*/
public Matrix2f(Matrix2f src) {
load(src);
}
/**
* Constructor
*/
public Matrix2f(Matrix2f src) {
load(src);
}
/**
* Load from another matrix
* @param src The source matrix
* @return this
*/
public Matrix2f load(Matrix2f src) {
return load(src, this);
}
/**
* Load from another matrix
* @param src The source matrix
* @return this
*/
public Matrix2f load(Matrix2f src) {
return load(src, this);
}
/**
* Copy the source matrix to the destination matrix.
* @param src The source matrix
* @param dest The destination matrix, or null if a new one should be created.
* @return The copied matrix
*/
public static Matrix2f load(Matrix2f src, Matrix2f dest) {
if (dest == null)
dest = new Matrix2f();
/**
* Copy the source matrix to the destination matrix.
* @param src The source matrix
* @param dest The destination matrix, or null if a new one should be created.
* @return The copied matrix
*/
public static Matrix2f load(Matrix2f src, Matrix2f dest) {
if (dest == null) dest = new Matrix2f();
dest.m00 = src.m00;
dest.m01 = src.m01;
dest.m10 = src.m10;
dest.m11 = src.m11;
dest.m00 = src.m00;
dest.m01 = src.m01;
dest.m10 = src.m10;
dest.m11 = src.m11;
return dest;
}
return dest;
}
/**
* Load from a float buffer. The buffer stores the matrix in column major
* (OpenGL) order.
*
* @param buf A float buffer to read from
* @return this
*/
public Matrix load(FloatBuffer buf) {
/**
* Load from a float buffer. The buffer stores the matrix in column major
* (OpenGL) order.
*
* @param buf A float buffer to read from
* @return this
*/
public Matrix load(FloatBuffer buf) {
m00 = buf.get();
m01 = buf.get();
m10 = buf.get();
m11 = buf.get();
m00 = buf.get();
m01 = buf.get();
m10 = buf.get();
m11 = buf.get();
return this;
}
return this;
}
/**
* Load from a float buffer. The buffer stores the matrix in row major
* (mathematical) order.
*
* @param buf A float buffer to read from
* @return this
*/
public Matrix loadTranspose(FloatBuffer buf) {
/**
* Load from a float buffer. The buffer stores the matrix in row major
* (mathematical) order.
*
* @param buf A float buffer to read from
* @return this
*/
public Matrix loadTranspose(FloatBuffer buf) {
m00 = buf.get();
m10 = buf.get();
m01 = buf.get();
m11 = buf.get();
m00 = buf.get();
m10 = buf.get();
m01 = buf.get();
m11 = buf.get();
return this;
}
return this;
}
/**
* Store this matrix in a float buffer. The matrix is stored in column
* major (openGL) order.
* @param buf The buffer to store this matrix in
*/
public Matrix store(FloatBuffer buf) {
buf.put(m00);
buf.put(m01);
buf.put(m10);
buf.put(m11);
return this;
}
/**
* Store this matrix in a float buffer. The matrix is stored in column
* major (openGL) order.
* @param buf The buffer to store this matrix in
*/
public Matrix store(FloatBuffer buf) {
buf.put(m00);
buf.put(m01);
buf.put(m10);
buf.put(m11);
return this;
}
/**
* Store this matrix in a float buffer. The matrix is stored in row
* major (maths) order.
* @param buf The buffer to store this matrix in
*/
public Matrix storeTranspose(FloatBuffer buf) {
buf.put(m00);
buf.put(m10);
buf.put(m01);
buf.put(m11);
return this;
}
/**
* Store this matrix in a float buffer. The matrix is stored in row
* major (maths) order.
* @param buf The buffer to store this matrix in
*/
public Matrix storeTranspose(FloatBuffer buf) {
buf.put(m00);
buf.put(m10);
buf.put(m01);
buf.put(m11);
return this;
}
/**
* Add two matrices together and place the result in a third matrix.
* @param left The left source matrix
* @param right The right source matrix
* @param dest The destination matrix, or null if a new one is to be created
* @return the destination matrix
*/
public static Matrix2f add(Matrix2f left, Matrix2f right, Matrix2f dest) {
if (dest == null) dest = new Matrix2f();
dest.m00 = left.m00 + right.m00;
dest.m01 = left.m01 + right.m01;
dest.m10 = left.m10 + right.m10;
dest.m11 = left.m11 + right.m11;
/**
* Add two matrices together and place the result in a third matrix.
* @param left The left source matrix
* @param right The right source matrix
* @param dest The destination matrix, or null if a new one is to be created
* @return the destination matrix
*/
public static Matrix2f add(Matrix2f left, Matrix2f right, Matrix2f dest) {
if (dest == null)
dest = new Matrix2f();
return dest;
}
dest.m00 = left.m00 + right.m00;
dest.m01 = left.m01 + right.m01;
dest.m10 = left.m10 + right.m10;
dest.m11 = left.m11 + right.m11;
/**
* Subtract the right matrix from the left and place the result in a third matrix.
* @param left The left source matrix
* @param right The right source matrix
* @param dest The destination matrix, or null if a new one is to be created
* @return the destination matrix
*/
public static Matrix2f sub(Matrix2f left, Matrix2f right, Matrix2f dest) {
if (dest == null) dest = new Matrix2f();
return dest;
}
dest.m00 = left.m00 - right.m00;
dest.m01 = left.m01 - right.m01;
dest.m10 = left.m10 - right.m10;
dest.m11 = left.m11 - right.m11;
/**
* Subtract the right matrix from the left and place the result in a third matrix.
* @param left The left source matrix
* @param right The right source matrix
* @param dest The destination matrix, or null if a new one is to be created
* @return the destination matrix
*/
public static Matrix2f sub(Matrix2f left, Matrix2f right, Matrix2f dest) {
if (dest == null)
dest = new Matrix2f();
return dest;
}
dest.m00 = left.m00 - right.m00;
dest.m01 = left.m01 - right.m01;
dest.m10 = left.m10 - right.m10;
dest.m11 = left.m11 - right.m11;
/**
* Multiply the right matrix by the left and place the result in a third matrix.
* @param left The left source matrix
* @param right The right source matrix
* @param dest The destination matrix, or null if a new one is to be created
* @return the destination matrix
*/
public static Matrix2f mul(Matrix2f left, Matrix2f right, Matrix2f dest) {
if (dest == null) dest = new Matrix2f();
return dest;
}
float m00 = left.m00 * right.m00 + left.m10 * right.m01;
float m01 = left.m01 * right.m00 + left.m11 * right.m01;
float m10 = left.m00 * right.m10 + left.m10 * right.m11;
float m11 = left.m01 * right.m10 + left.m11 * right.m11;
/**
* Multiply the right matrix by the left and place the result in a third matrix.
* @param left The left source matrix
* @param right The right source matrix
* @param dest The destination matrix, or null if a new one is to be created
* @return the destination matrix
*/
public static Matrix2f mul(Matrix2f left, Matrix2f right, Matrix2f dest) {
if (dest == null)
dest = new Matrix2f();
dest.m00 = m00;
dest.m01 = m01;
dest.m10 = m10;
dest.m11 = m11;
float m00 = left.m00 * right.m00 + left.m10 * right.m01;
float m01 = left.m01 * right.m00 + left.m11 * right.m01;
float m10 = left.m00 * right.m10 + left.m10 * right.m11;
float m11 = left.m01 * right.m10 + left.m11 * right.m11;
return dest;
}
dest.m00 = m00;
dest.m01 = m01;
dest.m10 = m10;
dest.m11 = m11;
/**
* Transform a Vector by a matrix and return the result in a destination
* vector.
* @param left The left matrix
* @param right The right vector
* @param dest The destination vector, or null if a new one is to be created
* @return the destination vector
*/
public static Vector2f transform(Matrix2f left, Vector2f right, Vector2f dest) {
if (dest == null) dest = new Vector2f();
return dest;
}
float x = left.m00 * right.x + left.m10 * right.y;
float y = left.m01 * right.x + left.m11 * right.y;
/**
* Transform a Vector by a matrix and return the result in a destination
* vector.
* @param left The left matrix
* @param right The right vector
* @param dest The destination vector, or null if a new one is to be created
* @return the destination vector
*/
public static Vector2f transform(Matrix2f left, Vector2f right, Vector2f dest) {
if (dest == null)
dest = new Vector2f();
dest.x = x;
dest.y = y;
float x = left.m00 * right.x + left.m10 * right.y;
float y = left.m01 * right.x + left.m11 * right.y;
return dest;
}
dest.x = x;
dest.y = y;
/**
* Transpose this matrix
* @return this
*/
public Matrix transpose() {
return transpose(this);
}
return dest;
}
/**
* Transpose this matrix and place the result in another matrix.
* @param dest The destination matrix or null if a new matrix is to be created
* @return the transposed matrix
*/
public Matrix2f transpose(Matrix2f dest) {
return transpose(this, dest);
}
/**
* Transpose this matrix
* @return this
*/
public Matrix transpose() {
return transpose(this);
}
/**
* Transpose the source matrix and place the result in the destination matrix.
* @param src The source matrix or null if a new matrix is to be created
* @param dest The destination matrix or null if a new matrix is to be created
* @return the transposed matrix
*/
public static Matrix2f transpose(Matrix2f src, Matrix2f dest) {
if (dest == null) dest = new Matrix2f();
/**
* Transpose this matrix and place the result in another matrix.
* @param dest The destination matrix or null if a new matrix is to be created
* @return the transposed matrix
*/
public Matrix2f transpose(Matrix2f dest) {
return transpose(this, dest);
}
float m01 = src.m10;
float m10 = src.m01;
/**
* Transpose the source matrix and place the result in the destination matrix.
* @param src The source matrix or null if a new matrix is to be created
* @param dest The destination matrix or null if a new matrix is to be created
* @return the transposed matrix
*/
public static Matrix2f transpose(Matrix2f src, Matrix2f dest) {
if (dest == null)
dest = new Matrix2f();
dest.m01 = m01;
dest.m10 = m10;
float m01 = src.m10;
float m10 = src.m01;
return dest;
}
dest.m01 = m01;
dest.m10 = m10;
/**
* Invert this matrix
* @return this if successful, null otherwise
*/
public Matrix invert() {
return invert(this, this);
}
return dest;
}
/**
* Invert the source matrix and place the result in the destination matrix.
* @param src The source matrix to be inverted
* @param dest The destination matrix or null if a new matrix is to be created
* @return The inverted matrix, or null if source can't be reverted.
*/
public static Matrix2f invert(Matrix2f src, Matrix2f dest) {
/*
*inv(A) = 1/det(A) * adj(A);
*/
/**
* Invert this matrix
* @return this if successful, null otherwise
*/
public Matrix invert() {
return invert(this, this);
}
float determinant = src.determinant();
if (determinant != 0) {
if (dest == null) dest = new Matrix2f();
float determinant_inv = 1f / determinant;
float t00 = src.m11 * determinant_inv;
float t01 = -src.m01 * determinant_inv;
float t11 = src.m00 * determinant_inv;
float t10 = -src.m10 * determinant_inv;
/**
* Invert the source matrix and place the result in the destination matrix.
* @param src The source matrix to be inverted
* @param dest The destination matrix or null if a new matrix is to be created
* @return The inverted matrix, or null if source can't be reverted.
*/
public static Matrix2f invert(Matrix2f src, Matrix2f dest) {
/*
*inv(A) = 1/det(A) * adj(A);
*/
dest.m00 = t00;
dest.m01 = t01;
dest.m10 = t10;
dest.m11 = t11;
return dest;
} else return null;
}
float determinant = src.determinant();
if (determinant != 0) {
if (dest == null)
dest = new Matrix2f();
float determinant_inv = 1f/determinant;
float t00 = src.m11*determinant_inv;
float t01 = -src.m01*determinant_inv;
float t11 = src.m00*determinant_inv;
float t10 = -src.m10*determinant_inv;
/**
* Returns a string representation of this matrix
*/
public String toString() {
StringBuilder buf = new StringBuilder();
buf.append(m00).append(' ').append(m10).append(' ').append('\n');
buf.append(m01).append(' ').append(m11).append(' ').append('\n');
return buf.toString();
}
dest.m00 = t00;
dest.m01 = t01;
dest.m10 = t10;
dest.m11 = t11;
return dest;
} else
return null;
}
/**
* Negate this matrix
* @return this
*/
public Matrix negate() {
return negate(this);
}
/**
* Returns a string representation of this matrix
*/
public String toString() {
StringBuilder buf = new StringBuilder();
buf.append(m00).append(' ').append(m10).append(' ').append('\n');
buf.append(m01).append(' ').append(m11).append(' ').append('\n');
return buf.toString();
}
/**
* Negate this matrix and stash the result in another matrix.
* @param dest The destination matrix, or null if a new matrix is to be created
* @return the negated matrix
*/
public Matrix2f negate(Matrix2f dest) {
return negate(this, dest);
}
/**
* Negate this matrix
* @return this
*/
public Matrix negate() {
return negate(this);
}
/**
* Negate the source matrix and stash the result in the destination matrix.
* @param src The source matrix to be negated
* @param dest The destination matrix, or null if a new matrix is to be created
* @return the negated matrix
*/
public static Matrix2f negate(Matrix2f src, Matrix2f dest) {
if (dest == null) dest = new Matrix2f();
/**
* Negate this matrix and stash the result in another matrix.
* @param dest The destination matrix, or null if a new matrix is to be created
* @return the negated matrix
*/
public Matrix2f negate(Matrix2f dest) {
return negate(this, dest);
}
dest.m00 = -src.m00;
dest.m01 = -src.m01;
dest.m10 = -src.m10;
dest.m11 = -src.m11;
/**
* Negate the source matrix and stash the result in the destination matrix.
* @param src The source matrix to be negated
* @param dest The destination matrix, or null if a new matrix is to be created
* @return the negated matrix
*/
public static Matrix2f negate(Matrix2f src, Matrix2f dest) {
if (dest == null)
dest = new Matrix2f();
return dest;
}
dest.m00 = -src.m00;
dest.m01 = -src.m01;
dest.m10 = -src.m10;
dest.m11 = -src.m11;
/**
* Set this matrix to be the identity matrix.
* @return this
*/
public Matrix setIdentity() {
return setIdentity(this);
}
return dest;
}
/**
* Set the source matrix to be the identity matrix.
* @param src The matrix to set to the identity.
* @return The source matrix
*/
public static Matrix2f setIdentity(Matrix2f src) {
src.m00 = 1.0f;
src.m01 = 0.0f;
src.m10 = 0.0f;
src.m11 = 1.0f;
return src;
}
/**
* Set this matrix to be the identity matrix.
* @return this
*/
public Matrix setIdentity() {
return setIdentity(this);
}
/**
* Set this matrix to 0.
* @return this
*/
public Matrix setZero() {
return setZero(this);
}
/**
* Set the source matrix to be the identity matrix.
* @param src The matrix to set to the identity.
* @return The source matrix
*/
public static Matrix2f setIdentity(Matrix2f src) {
src.m00 = 1.0f;
src.m01 = 0.0f;
src.m10 = 0.0f;
src.m11 = 1.0f;
return src;
}
public static Matrix2f setZero(Matrix2f src) {
src.m00 = 0.0f;
src.m01 = 0.0f;
src.m10 = 0.0f;
src.m11 = 0.0f;
return src;
}
/**
* Set this matrix to 0.
* @return this
*/
public Matrix setZero() {
return setZero(this);
}
public static Matrix2f setZero(Matrix2f src) {
src.m00 = 0.0f;
src.m01 = 0.0f;
src.m10 = 0.0f;
src.m11 = 0.0f;
return src;
}
/* (non-Javadoc)
* @see org.lwjgl.vector.Matrix#determinant()
*/
public float determinant() {
return m00 * m11 - m01*m10;
}
/* (non-Javadoc)
* @see org.lwjgl.vector.Matrix#determinant()
*/
public float determinant() {
return m00 * m11 - m01 * m10;
}
}
+403 -416
View File
@@ -42,469 +42,456 @@ import java.nio.FloatBuffer;
* @version $Revision: 3799 $
* $Id: Matrix3f.java 3799 2012-09-12 11:29:40Z kappa1 $
*/
public class Matrix3f extends Matrix implements Serializable {
private static final long serialVersionUID = 1L;
private static final long serialVersionUID = 1L;
public float m00,
m01,
m02,
m10,
m11,
m12,
m20,
m21,
m22;
public float m00, m01, m02, m10, m11, m12, m20, m21, m22;
/**
* Constructor for Matrix3f. Matrix is initialised to the identity.
*/
public Matrix3f() {
super();
setIdentity();
}
/**
* Constructor for Matrix3f. Matrix is initialised to the identity.
*/
public Matrix3f() {
super();
setIdentity();
}
/**
* Load from another matrix
* @param src The source matrix
* @return this
*/
public Matrix3f load(Matrix3f src) {
return load(src, this);
}
/**
* Load from another matrix
* @param src The source matrix
* @return this
*/
public Matrix3f load(Matrix3f src) {
return load(src, this);
}
/**
* Copy source matrix to destination matrix
* @param src The source matrix
* @param dest The destination matrix, or null of a new matrix is to be created
* @return The copied matrix
*/
public static Matrix3f load(Matrix3f src, Matrix3f dest) {
if (dest == null)
dest = new Matrix3f();
/**
* Copy source matrix to destination matrix
* @param src The source matrix
* @param dest The destination matrix, or null of a new matrix is to be created
* @return The copied matrix
*/
public static Matrix3f load(Matrix3f src, Matrix3f dest) {
if (dest == null) dest = new Matrix3f();
dest.m00 = src.m00;
dest.m10 = src.m10;
dest.m20 = src.m20;
dest.m01 = src.m01;
dest.m11 = src.m11;
dest.m21 = src.m21;
dest.m02 = src.m02;
dest.m12 = src.m12;
dest.m22 = src.m22;
dest.m00 = src.m00;
dest.m10 = src.m10;
dest.m20 = src.m20;
dest.m01 = src.m01;
dest.m11 = src.m11;
dest.m21 = src.m21;
dest.m02 = src.m02;
dest.m12 = src.m12;
dest.m22 = src.m22;
return dest;
}
return dest;
}
/**
* Load from a float buffer. The buffer stores the matrix in column major
* (OpenGL) order.
*
* @param buf A float buffer to read from
* @return this
*/
public Matrix load(FloatBuffer buf) {
/**
* Load from a float buffer. The buffer stores the matrix in column major
* (OpenGL) order.
*
* @param buf A float buffer to read from
* @return this
*/
public Matrix load(FloatBuffer buf) {
m00 = buf.get();
m01 = buf.get();
m02 = buf.get();
m10 = buf.get();
m11 = buf.get();
m12 = buf.get();
m20 = buf.get();
m21 = buf.get();
m22 = buf.get();
m00 = buf.get();
m01 = buf.get();
m02 = buf.get();
m10 = buf.get();
m11 = buf.get();
m12 = buf.get();
m20 = buf.get();
m21 = buf.get();
m22 = buf.get();
return this;
}
return this;
}
/**
* Load from a float buffer. The buffer stores the matrix in row major
* (maths) order.
*
* @param buf A float buffer to read from
* @return this
*/
public Matrix loadTranspose(FloatBuffer buf) {
/**
* Load from a float buffer. The buffer stores the matrix in row major
* (maths) order.
*
* @param buf A float buffer to read from
* @return this
*/
public Matrix loadTranspose(FloatBuffer buf) {
m00 = buf.get();
m10 = buf.get();
m20 = buf.get();
m01 = buf.get();
m11 = buf.get();
m21 = buf.get();
m02 = buf.get();
m12 = buf.get();
m22 = buf.get();
m00 = buf.get();
m10 = buf.get();
m20 = buf.get();
m01 = buf.get();
m11 = buf.get();
m21 = buf.get();
m02 = buf.get();
m12 = buf.get();
m22 = buf.get();
return this;
}
return this;
}
/**
* Store this matrix in a float buffer. The matrix is stored in column
* major (openGL) order.
* @param buf The buffer to store this matrix in
*/
public Matrix store(FloatBuffer buf) {
buf.put(m00);
buf.put(m01);
buf.put(m02);
buf.put(m10);
buf.put(m11);
buf.put(m12);
buf.put(m20);
buf.put(m21);
buf.put(m22);
return this;
}
/**
* Store this matrix in a float buffer. The matrix is stored in column
* major (openGL) order.
* @param buf The buffer to store this matrix in
*/
public Matrix store(FloatBuffer buf) {
buf.put(m00);
buf.put(m01);
buf.put(m02);
buf.put(m10);
buf.put(m11);
buf.put(m12);
buf.put(m20);
buf.put(m21);
buf.put(m22);
return this;
}
/**
* Store this matrix in a float buffer. The matrix is stored in row
* major (maths) order.
* @param buf The buffer to store this matrix in
*/
public Matrix storeTranspose(FloatBuffer buf) {
buf.put(m00);
buf.put(m10);
buf.put(m20);
buf.put(m01);
buf.put(m11);
buf.put(m21);
buf.put(m02);
buf.put(m12);
buf.put(m22);
return this;
}
/**
* Store this matrix in a float buffer. The matrix is stored in row
* major (maths) order.
* @param buf The buffer to store this matrix in
*/
public Matrix storeTranspose(FloatBuffer buf) {
buf.put(m00);
buf.put(m10);
buf.put(m20);
buf.put(m01);
buf.put(m11);
buf.put(m21);
buf.put(m02);
buf.put(m12);
buf.put(m22);
return this;
}
/**
* Add two matrices together and place the result in a third matrix.
* @param left The left source matrix
* @param right The right source matrix
* @param dest The destination matrix, or null if a new one is to be created
* @return the destination matrix
*/
public static Matrix3f add(Matrix3f left, Matrix3f right, Matrix3f dest) {
if (dest == null)
dest = new Matrix3f();
/**
* Add two matrices together and place the result in a third matrix.
* @param left The left source matrix
* @param right The right source matrix
* @param dest The destination matrix, or null if a new one is to be created
* @return the destination matrix
*/
public static Matrix3f add(Matrix3f left, Matrix3f right, Matrix3f dest) {
if (dest == null) dest = new Matrix3f();
dest.m00 = left.m00 + right.m00;
dest.m01 = left.m01 + right.m01;
dest.m02 = left.m02 + right.m02;
dest.m10 = left.m10 + right.m10;
dest.m11 = left.m11 + right.m11;
dest.m12 = left.m12 + right.m12;
dest.m20 = left.m20 + right.m20;
dest.m21 = left.m21 + right.m21;
dest.m22 = left.m22 + right.m22;
dest.m00 = left.m00 + right.m00;
dest.m01 = left.m01 + right.m01;
dest.m02 = left.m02 + right.m02;
dest.m10 = left.m10 + right.m10;
dest.m11 = left.m11 + right.m11;
dest.m12 = left.m12 + right.m12;
dest.m20 = left.m20 + right.m20;
dest.m21 = left.m21 + right.m21;
dest.m22 = left.m22 + right.m22;
return dest;
}
return dest;
}
/**
* Subtract the right matrix from the left and place the result in a third matrix.
* @param left The left source matrix
* @param right The right source matrix
* @param dest The destination matrix, or null if a new one is to be created
* @return the destination matrix
*/
public static Matrix3f sub(Matrix3f left, Matrix3f right, Matrix3f dest) {
if (dest == null)
dest = new Matrix3f();
/**
* Subtract the right matrix from the left and place the result in a third matrix.
* @param left The left source matrix
* @param right The right source matrix
* @param dest The destination matrix, or null if a new one is to be created
* @return the destination matrix
*/
public static Matrix3f sub(Matrix3f left, Matrix3f right, Matrix3f dest) {
if (dest == null) dest = new Matrix3f();
dest.m00 = left.m00 - right.m00;
dest.m01 = left.m01 - right.m01;
dest.m02 = left.m02 - right.m02;
dest.m10 = left.m10 - right.m10;
dest.m11 = left.m11 - right.m11;
dest.m12 = left.m12 - right.m12;
dest.m20 = left.m20 - right.m20;
dest.m21 = left.m21 - right.m21;
dest.m22 = left.m22 - right.m22;
dest.m00 = left.m00 - right.m00;
dest.m01 = left.m01 - right.m01;
dest.m02 = left.m02 - right.m02;
dest.m10 = left.m10 - right.m10;
dest.m11 = left.m11 - right.m11;
dest.m12 = left.m12 - right.m12;
dest.m20 = left.m20 - right.m20;
dest.m21 = left.m21 - right.m21;
dest.m22 = left.m22 - right.m22;
return dest;
}
return dest;
}
/**
* Multiply the right matrix by the left and place the result in a third matrix.
* @param left The left source matrix
* @param right The right source matrix
* @param dest The destination matrix, or null if a new one is to be created
* @return the destination matrix
*/
public static Matrix3f mul(Matrix3f left, Matrix3f right, Matrix3f dest) {
if (dest == null)
dest = new Matrix3f();
/**
* Multiply the right matrix by the left and place the result in a third matrix.
* @param left The left source matrix
* @param right The right source matrix
* @param dest The destination matrix, or null if a new one is to be created
* @return the destination matrix
*/
public static Matrix3f mul(Matrix3f left, Matrix3f right, Matrix3f dest) {
if (dest == null) dest = new Matrix3f();
float m00 =
left.m00 * right.m00 + left.m10 * right.m01 + left.m20 * right.m02;
float m01 =
left.m01 * right.m00 + left.m11 * right.m01 + left.m21 * right.m02;
float m02 =
left.m02 * right.m00 + left.m12 * right.m01 + left.m22 * right.m02;
float m10 =
left.m00 * right.m10 + left.m10 * right.m11 + left.m20 * right.m12;
float m11 =
left.m01 * right.m10 + left.m11 * right.m11 + left.m21 * right.m12;
float m12 =
left.m02 * right.m10 + left.m12 * right.m11 + left.m22 * right.m12;
float m20 =
left.m00 * right.m20 + left.m10 * right.m21 + left.m20 * right.m22;
float m21 =
left.m01 * right.m20 + left.m11 * right.m21 + left.m21 * right.m22;
float m22 =
left.m02 * right.m20 + left.m12 * right.m21 + left.m22 * right.m22;
float m00 = left.m00 * right.m00 + left.m10 * right.m01 + left.m20 * right.m02;
float m01 = left.m01 * right.m00 + left.m11 * right.m01 + left.m21 * right.m02;
float m02 = left.m02 * right.m00 + left.m12 * right.m01 + left.m22 * right.m02;
float m10 = left.m00 * right.m10 + left.m10 * right.m11 + left.m20 * right.m12;
float m11 = left.m01 * right.m10 + left.m11 * right.m11 + left.m21 * right.m12;
float m12 = left.m02 * right.m10 + left.m12 * right.m11 + left.m22 * right.m12;
float m20 = left.m00 * right.m20 + left.m10 * right.m21 + left.m20 * right.m22;
float m21 = left.m01 * right.m20 + left.m11 * right.m21 + left.m21 * right.m22;
float m22 = left.m02 * right.m20 + left.m12 * right.m21 + left.m22 * right.m22;
dest.m00 = m00;
dest.m01 = m01;
dest.m02 = m02;
dest.m10 = m10;
dest.m11 = m11;
dest.m12 = m12;
dest.m20 = m20;
dest.m21 = m21;
dest.m22 = m22;
dest.m00 = m00;
dest.m01 = m01;
dest.m02 = m02;
dest.m10 = m10;
dest.m11 = m11;
dest.m12 = m12;
dest.m20 = m20;
dest.m21 = m21;
dest.m22 = m22;
return dest;
}
return dest;
}
/**
* Transform a Vector by a matrix and return the result in a destination
* vector.
* @param left The left matrix
* @param right The right vector
* @param dest The destination vector, or null if a new one is to be created
* @return the destination vector
*/
public static Vector3f transform(Matrix3f left, Vector3f right, Vector3f dest) {
if (dest == null)
dest = new Vector3f();
/**
* Transform a Vector by a matrix and return the result in a destination
* vector.
* @param left The left matrix
* @param right The right vector
* @param dest The destination vector, or null if a new one is to be created
* @return the destination vector
*/
public static Vector3f transform(Matrix3f left, Vector3f right, Vector3f dest) {
if (dest == null) dest = new Vector3f();
float x = left.m00 * right.x + left.m10 * right.y + left.m20 * right.z;
float y = left.m01 * right.x + left.m11 * right.y + left.m21 * right.z;
float z = left.m02 * right.x + left.m12 * right.y + left.m22 * right.z;
float x = left.m00 * right.x + left.m10 * right.y + left.m20 * right.z;
float y = left.m01 * right.x + left.m11 * right.y + left.m21 * right.z;
float z = left.m02 * right.x + left.m12 * right.y + left.m22 * right.z;
dest.x = x;
dest.y = y;
dest.z = z;
dest.x = x;
dest.y = y;
dest.z = z;
return dest;
}
return dest;
}
/**
* Transpose this matrix
* @return this
*/
public Matrix transpose() {
return transpose(this, this);
}
/**
* Transpose this matrix
* @return this
*/
public Matrix transpose() {
return transpose(this, this);
}
/**
* Transpose this matrix and place the result in another matrix
* @param dest The destination matrix or null if a new matrix is to be created
* @return the transposed matrix
*/
public Matrix3f transpose(Matrix3f dest) {
return transpose(this, dest);
}
/**
* Transpose this matrix and place the result in another matrix
* @param dest The destination matrix or null if a new matrix is to be created
* @return the transposed matrix
*/
public Matrix3f transpose(Matrix3f dest) {
return transpose(this, dest);
}
/**
* Transpose the source matrix and place the result into the destination matrix
* @param src The source matrix to be transposed
* @param dest The destination matrix or null if a new matrix is to be created
* @return the transposed matrix
*/
public static Matrix3f transpose(Matrix3f src, Matrix3f dest) {
if (dest == null)
dest = new Matrix3f();
float m00 = src.m00;
float m01 = src.m10;
float m02 = src.m20;
float m10 = src.m01;
float m11 = src.m11;
float m12 = src.m21;
float m20 = src.m02;
float m21 = src.m12;
float m22 = src.m22;
/**
* Transpose the source matrix and place the result into the destination matrix
* @param src The source matrix to be transposed
* @param dest The destination matrix or null if a new matrix is to be created
* @return the transposed matrix
*/
public static Matrix3f transpose(Matrix3f src, Matrix3f dest) {
if (dest == null) dest = new Matrix3f();
float m00 = src.m00;
float m01 = src.m10;
float m02 = src.m20;
float m10 = src.m01;
float m11 = src.m11;
float m12 = src.m21;
float m20 = src.m02;
float m21 = src.m12;
float m22 = src.m22;
dest.m00 = m00;
dest.m01 = m01;
dest.m02 = m02;
dest.m10 = m10;
dest.m11 = m11;
dest.m12 = m12;
dest.m20 = m20;
dest.m21 = m21;
dest.m22 = m22;
return dest;
}
dest.m00 = m00;
dest.m01 = m01;
dest.m02 = m02;
dest.m10 = m10;
dest.m11 = m11;
dest.m12 = m12;
dest.m20 = m20;
dest.m21 = m21;
dest.m22 = m22;
return dest;
}
/**
* @return the determinant of the matrix
*/
public float determinant() {
float f =
m00 * (m11 * m22 - m12 * m21)
+ m01 * (m12 * m20 - m10 * m22)
+ m02 * (m10 * m21 - m11 * m20);
return f;
}
/**
* @return the determinant of the matrix
*/
public float determinant() {
float f = m00 * (m11 * m22 - m12 * m21) + m01 * (m12 * m20 - m10 * m22) + m02 * (m10 * m21 - m11 * m20);
return f;
}
/**
* Returns a string representation of this matrix
*/
public String toString() {
StringBuilder buf = new StringBuilder();
buf.append(m00).append(' ').append(m10).append(' ').append(m20).append(' ').append('\n');
buf.append(m01).append(' ').append(m11).append(' ').append(m21).append(' ').append('\n');
buf.append(m02).append(' ').append(m12).append(' ').append(m22).append(' ').append('\n');
return buf.toString();
}
/**
* Returns a string representation of this matrix
*/
public String toString() {
StringBuilder buf = new StringBuilder();
buf.append(m00)
.append(' ')
.append(m10)
.append(' ')
.append(m20)
.append(' ')
.append('\n');
buf.append(m01)
.append(' ')
.append(m11)
.append(' ')
.append(m21)
.append(' ')
.append('\n');
buf.append(m02)
.append(' ')
.append(m12)
.append(' ')
.append(m22)
.append(' ')
.append('\n');
return buf.toString();
}
/**
* Invert this matrix
* @return this if successful, null otherwise
*/
public Matrix invert() {
return invert(this, this);
}
/**
* Invert this matrix
* @return this if successful, null otherwise
*/
public Matrix invert() {
return invert(this, this);
}
/**
* Invert the source matrix and put the result into the destination matrix
* @param src The source matrix to be inverted
* @param dest The destination matrix, or null if a new one is to be created
* @return The inverted matrix if successful, null otherwise
*/
public static Matrix3f invert(Matrix3f src, Matrix3f dest) {
float determinant = src.determinant();
/**
* Invert the source matrix and put the result into the destination matrix
* @param src The source matrix to be inverted
* @param dest The destination matrix, or null if a new one is to be created
* @return The inverted matrix if successful, null otherwise
*/
public static Matrix3f invert(Matrix3f src, Matrix3f dest) {
float determinant = src.determinant();
if (determinant != 0) {
if (dest == null)
dest = new Matrix3f();
/* do it the ordinary way
*
* inv(A) = 1/det(A) * adj(T), where adj(T) = transpose(Conjugate Matrix)
*
* m00 m01 m02
* m10 m11 m12
* m20 m21 m22
*/
float determinant_inv = 1f/determinant;
if (determinant != 0) {
if (dest == null) dest = new Matrix3f();
/* do it the ordinary way
*
* inv(A) = 1/det(A) * adj(T), where adj(T) = transpose(Conjugate Matrix)
*
* m00 m01 m02
* m10 m11 m12
* m20 m21 m22
*/
float determinant_inv = 1f / determinant;
// get the conjugate matrix
float t00 = src.m11 * src.m22 - src.m12* src.m21;
float t01 = - src.m10 * src.m22 + src.m12 * src.m20;
float t02 = src.m10 * src.m21 - src.m11 * src.m20;
float t10 = - src.m01 * src.m22 + src.m02 * src.m21;
float t11 = src.m00 * src.m22 - src.m02 * src.m20;
float t12 = - src.m00 * src.m21 + src.m01 * src.m20;
float t20 = src.m01 * src.m12 - src.m02 * src.m11;
float t21 = -src.m00 * src.m12 + src.m02 * src.m10;
float t22 = src.m00 * src.m11 - src.m01 * src.m10;
// get the conjugate matrix
float t00 = src.m11 * src.m22 - src.m12 * src.m21;
float t01 = -src.m10 * src.m22 + src.m12 * src.m20;
float t02 = src.m10 * src.m21 - src.m11 * src.m20;
float t10 = -src.m01 * src.m22 + src.m02 * src.m21;
float t11 = src.m00 * src.m22 - src.m02 * src.m20;
float t12 = -src.m00 * src.m21 + src.m01 * src.m20;
float t20 = src.m01 * src.m12 - src.m02 * src.m11;
float t21 = -src.m00 * src.m12 + src.m02 * src.m10;
float t22 = src.m00 * src.m11 - src.m01 * src.m10;
dest.m00 = t00*determinant_inv;
dest.m11 = t11*determinant_inv;
dest.m22 = t22*determinant_inv;
dest.m01 = t10*determinant_inv;
dest.m10 = t01*determinant_inv;
dest.m20 = t02*determinant_inv;
dest.m02 = t20*determinant_inv;
dest.m12 = t21*determinant_inv;
dest.m21 = t12*determinant_inv;
return dest;
} else
return null;
}
dest.m00 = t00 * determinant_inv;
dest.m11 = t11 * determinant_inv;
dest.m22 = t22 * determinant_inv;
dest.m01 = t10 * determinant_inv;
dest.m10 = t01 * determinant_inv;
dest.m20 = t02 * determinant_inv;
dest.m02 = t20 * determinant_inv;
dest.m12 = t21 * determinant_inv;
dest.m21 = t12 * determinant_inv;
return dest;
} else return null;
}
/**
* Negate this matrix
* @return this
*/
public Matrix negate() {
return negate(this);
}
/**
* Negate this matrix
* @return this
*/
public Matrix negate() {
return negate(this);
}
/**
* Negate this matrix and place the result in a destination matrix.
* @param dest The destination matrix, or null if a new matrix is to be created
* @return the negated matrix
*/
public Matrix3f negate(Matrix3f dest) {
return negate(this, dest);
}
/**
* Negate this matrix and place the result in a destination matrix.
* @param dest The destination matrix, or null if a new matrix is to be created
* @return the negated matrix
*/
public Matrix3f negate(Matrix3f dest) {
return negate(this, dest);
}
/**
* Negate the source matrix and place the result in the destination matrix.
* @param src The source matrix
* @param dest The destination matrix, or null if a new matrix is to be created
* @return the negated matrix
*/
public static Matrix3f negate(Matrix3f src, Matrix3f dest) {
if (dest == null) dest = new Matrix3f();
/**
* Negate the source matrix and place the result in the destination matrix.
* @param src The source matrix
* @param dest The destination matrix, or null if a new matrix is to be created
* @return the negated matrix
*/
public static Matrix3f negate(Matrix3f src, Matrix3f dest) {
if (dest == null)
dest = new Matrix3f();
dest.m00 = -src.m00;
dest.m01 = -src.m02;
dest.m02 = -src.m01;
dest.m10 = -src.m10;
dest.m11 = -src.m12;
dest.m12 = -src.m11;
dest.m20 = -src.m20;
dest.m21 = -src.m22;
dest.m22 = -src.m21;
return dest;
}
dest.m00 = -src.m00;
dest.m01 = -src.m02;
dest.m02 = -src.m01;
dest.m10 = -src.m10;
dest.m11 = -src.m12;
dest.m12 = -src.m11;
dest.m20 = -src.m20;
dest.m21 = -src.m22;
dest.m22 = -src.m21;
return dest;
}
/**
* Set this matrix to be the identity matrix.
* @return this
*/
public Matrix setIdentity() {
return setIdentity(this);
}
/**
* Set this matrix to be the identity matrix.
* @return this
*/
public Matrix setIdentity() {
return setIdentity(this);
}
/**
* Set the matrix to be the identity matrix.
* @param m The matrix to be set to the identity
* @return m
*/
public static Matrix3f setIdentity(Matrix3f m) {
m.m00 = 1.0f;
m.m01 = 0.0f;
m.m02 = 0.0f;
m.m10 = 0.0f;
m.m11 = 1.0f;
m.m12 = 0.0f;
m.m20 = 0.0f;
m.m21 = 0.0f;
m.m22 = 1.0f;
return m;
}
/**
* Set the matrix to be the identity matrix.
* @param m The matrix to be set to the identity
* @return m
*/
public static Matrix3f setIdentity(Matrix3f m) {
m.m00 = 1.0f;
m.m01 = 0.0f;
m.m02 = 0.0f;
m.m10 = 0.0f;
m.m11 = 1.0f;
m.m12 = 0.0f;
m.m20 = 0.0f;
m.m21 = 0.0f;
m.m22 = 1.0f;
return m;
}
/**
* Set this matrix to 0.
* @return this
*/
public Matrix setZero() {
return setZero(this);
}
/**
* Set this matrix to 0.
* @return this
*/
public Matrix setZero() {
return setZero(this);
}
/**
* Set the matrix matrix to 0.
* @param m The matrix to be set to 0
* @return m
*/
public static Matrix3f setZero(Matrix3f m) {
m.m00 = 0.0f;
m.m01 = 0.0f;
m.m02 = 0.0f;
m.m10 = 0.0f;
m.m11 = 0.0f;
m.m12 = 0.0f;
m.m20 = 0.0f;
m.m21 = 0.0f;
m.m22 = 0.0f;
return m;
}
/**
* Set the matrix matrix to 0.
* @param m The matrix to be set to 0
* @return m
*/
public static Matrix3f setZero(Matrix3f m) {
m.m00 = 0.0f;
m.m01 = 0.0f;
m.m02 = 0.0f;
m.m10 = 0.0f;
m.m11 = 0.0f;
m.m12 = 0.0f;
m.m20 = 0.0f;
m.m21 = 0.0f;
m.m22 = 0.0f;
return m;
}
}
File diff suppressed because it is too large. Load diff
@@ -39,492 +39,475 @@ package org.lwjglx.util.vector;
* @version $Revision: 3418 $
* $Id: Quaternion.java 3418 2010-09-28 21:11:35Z spasi $
*/
import java.nio.FloatBuffer;
public class Quaternion extends Vector implements ReadableVector4f {
private static final long serialVersionUID = 1L;
private static final long serialVersionUID = 1L;
public float x, y, z, w;
public float x, y, z, w;
/**
* C'tor. The quaternion will be initialized to the identity.
*/
public Quaternion() {
super();
setIdentity();
}
/**
* C'tor. The quaternion will be initialized to the identity.
*/
public Quaternion() {
super();
setIdentity();
}
/**
* C'tor
*
* @param src
*/
public Quaternion(ReadableVector4f src) {
set(src);
}
/**
* C'tor
*
* @param src
*/
public Quaternion(ReadableVector4f src) {
set(src);
}
/**
* C'tor
*
*/
public Quaternion(float x, float y, float z, float w) {
set(x, y, z, w);
}
/**
* C'tor
*
*/
public Quaternion(float x, float y, float z, float w) {
set(x, y, z, w);
}
/*
* (non-Javadoc)
*
* @see org.lwjgl.util.vector.WritableVector2f#set(float, float)
*/
public void set(float x, float y) {
this.x = x;
this.y = y;
}
/*
* (non-Javadoc)
*
* @see org.lwjgl.util.vector.WritableVector2f#set(float, float)
*/
public void set(float x, float y) {
this.x = x;
this.y = y;
}
/*
* (non-Javadoc)
*
* @see org.lwjgl.util.vector.WritableVector3f#set(float, float, float)
*/
public void set(float x, float y, float z) {
this.x = x;
this.y = y;
this.z = z;
}
/*
* (non-Javadoc)
*
* @see org.lwjgl.util.vector.WritableVector3f#set(float, float, float)
*/
public void set(float x, float y, float z) {
this.x = x;
this.y = y;
this.z = z;
}
/*
* (non-Javadoc)
*
* @see org.lwjgl.util.vector.WritableVector4f#set(float, float, float,
* float)
*/
public void set(float x, float y, float z, float w) {
this.x = x;
this.y = y;
this.z = z;
this.w = w;
}
/*
* (non-Javadoc)
*
* @see org.lwjgl.util.vector.WritableVector4f#set(float, float, float,
* float)
*/
public void set(float x, float y, float z, float w) {
this.x = x;
this.y = y;
this.z = z;
this.w = w;
}
/**
* Load from another Vector4f
*
* @param src
* The source vector
* @return this
*/
public Quaternion set(ReadableVector4f src) {
x = src.getX();
y = src.getY();
z = src.getZ();
w = src.getW();
return this;
}
/**
* Load from another Vector4f
*
* @param src
* The source vector
* @return this
*/
public Quaternion set(ReadableVector4f src) {
x = src.getX();
y = src.getY();
z = src.getZ();
w = src.getW();
return this;
}
/**
* Set this quaternion to the multiplication identity.
* @return this
*/
public Quaternion setIdentity() {
return setIdentity(this);
}
/**
* Set this quaternion to the multiplication identity.
* @return this
*/
public Quaternion setIdentity() {
return setIdentity(this);
}
/**
* Set the given quaternion to the multiplication identity.
* @param q The quaternion
* @return q
*/
public static Quaternion setIdentity(Quaternion q) {
q.x = 0;
q.y = 0;
q.z = 0;
q.w = 1;
return q;
}
/**
* Set the given quaternion to the multiplication identity.
* @param q The quaternion
* @return q
*/
public static Quaternion setIdentity(Quaternion q) {
q.x = 0;
q.y = 0;
q.z = 0;
q.w = 1;
return q;
}
/**
* @return the length squared of the quaternion
*/
public float lengthSquared() {
return x * x + y * y + z * z + w * w;
}
/**
* @return the length squared of the quaternion
*/
public float lengthSquared() {
return x * x + y * y + z * z + w * w;
}
/**
* Normalise the source quaternion and place the result in another quaternion.
*
* @param src
* The source quaternion
* @param dest
* The destination quaternion, or null if a new quaternion is to be
* created
* @return The normalised quaternion
*/
public static Quaternion normalise(Quaternion src, Quaternion dest) {
float inv_l = 1f/src.length();
/**
* Normalise the source quaternion and place the result in another quaternion.
*
* @param src
* The source quaternion
* @param dest
* The destination quaternion, or null if a new quaternion is to be
* created
* @return The normalised quaternion
*/
public static Quaternion normalise(Quaternion src, Quaternion dest) {
float inv_l = 1f / src.length();
if (dest == null)
dest = new Quaternion();
if (dest == null) dest = new Quaternion();
dest.set(src.x * inv_l, src.y * inv_l, src.z * inv_l, src.w * inv_l);
dest.set(src.x * inv_l, src.y * inv_l, src.z * inv_l, src.w * inv_l);
return dest;
}
return dest;
}
/**
* Normalise this quaternion and place the result in another quaternion.
*
* @param dest
* The destination quaternion, or null if a new quaternion is to be
* created
* @return the normalised quaternion
*/
public Quaternion normalise(Quaternion dest) {
return normalise(this, dest);
}
/**
* Normalise this quaternion and place the result in another quaternion.
*
* @param dest
* The destination quaternion, or null if a new quaternion is to be
* created
* @return the normalised quaternion
*/
public Quaternion normalise(Quaternion dest) {
return normalise(this, dest);
}
/**
* The dot product of two quaternions
*
* @param left
* The LHS quat
* @param right
* The RHS quat
* @return left dot right
*/
public static float dot(Quaternion left, Quaternion right) {
return left.x * right.x + left.y * right.y + left.z * right.z + left.w
* right.w;
}
/**
* The dot product of two quaternions
*
* @param left
* The LHS quat
* @param right
* The RHS quat
* @return left dot right
*/
public static float dot(Quaternion left, Quaternion right) {
return left.x * right.x + left.y * right.y + left.z * right.z + left.w * right.w;
}
/**
* Calculate the conjugate of this quaternion and put it into the given one
*
* @param dest
* The quaternion which should be set to the conjugate of this
* quaternion
*/
public Quaternion negate(Quaternion dest) {
return negate(this, dest);
}
/**
* Calculate the conjugate of this quaternion and put it into the given one
*
* @param dest
* The quaternion which should be set to the conjugate of this
* quaternion
*/
public Quaternion negate(Quaternion dest) {
return negate(this, dest);
}
/**
* Calculate the conjugate of this quaternion and put it into the given one
*
* @param src
* The source quaternion
* @param dest
* The quaternion which should be set to the conjugate of this
* quaternion
*/
public static Quaternion negate(Quaternion src, Quaternion dest) {
if (dest == null)
dest = new Quaternion();
/**
* Calculate the conjugate of this quaternion and put it into the given one
*
* @param src
* The source quaternion
* @param dest
* The quaternion which should be set to the conjugate of this
* quaternion
*/
public static Quaternion negate(Quaternion src, Quaternion dest) {
if (dest == null) dest = new Quaternion();
dest.x = -src.x;
dest.y = -src.y;
dest.z = -src.z;
dest.w = src.w;
dest.x = -src.x;
dest.y = -src.y;
dest.z = -src.z;
dest.w = src.w;
return dest;
}
return dest;
}
/**
* Calculate the conjugate of this quaternion
*/
public Vector negate() {
return negate(this, this);
}
/**
* Calculate the conjugate of this quaternion
*/
public Vector negate() {
return negate(this, this);
}
/* (non-Javadoc)
* @see org.lwjgl.util.vector.Vector#load(java.nio.FloatBuffer)
*/
public Vector load(FloatBuffer buf) {
x = buf.get();
y = buf.get();
z = buf.get();
w = buf.get();
return this;
}
/* (non-Javadoc)
* @see org.lwjgl.util.vector.Vector#load(java.nio.FloatBuffer)
*/
public Vector load(FloatBuffer buf) {
x = buf.get();
y = buf.get();
z = buf.get();
w = buf.get();
return this;
}
/*
* (non-Javadoc)
*
* @see org.lwjgl.vector.Vector#scale(float)
*/
public Vector scale(float scale) {
return scale(scale, this, this);
}
/*
* (non-Javadoc)
*
* @see org.lwjgl.vector.Vector#scale(float)
*/
public Vector scale(float scale) {
return scale(scale, this, this);
}
/**
* Scale the source quaternion by scale and put the result in the destination
* @param scale The amount to scale by
* @param src The source quaternion
* @param dest The destination quaternion, or null if a new quaternion is to be created
* @return The scaled quaternion
*/
public static Quaternion scale(float scale, Quaternion src, Quaternion dest) {
if (dest == null)
dest = new Quaternion();
dest.x = src.x * scale;
dest.y = src.y * scale;
dest.z = src.z * scale;
dest.w = src.w * scale;
return dest;
}
/**
* Scale the source quaternion by scale and put the result in the destination
* @param scale The amount to scale by
* @param src The source quaternion
* @param dest The destination quaternion, or null if a new quaternion is to be created
* @return The scaled quaternion
*/
public static Quaternion scale(float scale, Quaternion src, Quaternion dest) {
if (dest == null) dest = new Quaternion();
dest.x = src.x * scale;
dest.y = src.y * scale;
dest.z = src.z * scale;
dest.w = src.w * scale;
return dest;
}
/* (non-Javadoc)
* @see org.lwjgl.util.vector.ReadableVector#store(java.nio.FloatBuffer)
*/
public Vector store(FloatBuffer buf) {
buf.put(x);
buf.put(y);
buf.put(z);
buf.put(w);
/* (non-Javadoc)
* @see org.lwjgl.util.vector.ReadableVector#store(java.nio.FloatBuffer)
*/
public Vector store(FloatBuffer buf) {
buf.put(x);
buf.put(y);
buf.put(z);
buf.put(w);
return this;
}
return this;
}
/**
* @return x
*/
public final float getX() {
return x;
}
/**
* @return x
*/
public final float getX() {
return x;
}
/**
* @return y
*/
public final float getY() {
return y;
}
/**
* @return y
*/
public final float getY() {
return y;
}
/**
* Set X
*
* @param x
*/
public final void setX(float x) {
this.x = x;
}
/**
* Set X
*
* @param x
*/
public final void setX(float x) {
this.x = x;
}
/**
* Set Y
*
* @param y
*/
public final void setY(float y) {
this.y = y;
}
/**
* Set Y
*
* @param y
*/
public final void setY(float y) {
this.y = y;
}
/**
* Set Z
*
* @param z
*/
public void setZ(float z) {
this.z = z;
}
/**
* Set Z
*
* @param z
*/
public void setZ(float z) {
this.z = z;
}
/*
* (Overrides)
*
* @see org.lwjgl.vector.ReadableVector3f#getZ()
*/
public float getZ() {
return z;
}
/*
* (Overrides)
*
* @see org.lwjgl.vector.ReadableVector3f#getZ()
*/
public float getZ() {
return z;
}
/**
* Set W
*
* @param w
*/
public void setW(float w) {
this.w = w;
}
/**
* Set W
*
* @param w
*/
public void setW(float w) {
this.w = w;
}
/*
* (Overrides)
*
* @see org.lwjgl.vector.ReadableVector3f#getW()
*/
public float getW() {
return w;
}
/*
* (Overrides)
*
* @see org.lwjgl.vector.ReadableVector3f#getW()
*/
public float getW() {
return w;
}
public String toString() {
return "Quaternion: " + x + " " + y + " " + z + " " + w;
}
public String toString() {
return "Quaternion: " + x + " " + y + " " + z + " " + w;
}
/**
* Sets the value of this quaternion to the quaternion product of
* quaternions left and right (this = left * right). Note that this is safe
* for aliasing (e.g. this can be left or right).
*
* @param left
* the first quaternion
* @param right
* the second quaternion
*/
public static Quaternion mul(Quaternion left, Quaternion right,
Quaternion dest) {
if (dest == null)
dest = new Quaternion();
dest.set(left.x * right.w + left.w * right.x + left.y * right.z
- left.z * right.y, left.y * right.w + left.w * right.y
+ left.z * right.x - left.x * right.z, left.z * right.w
+ left.w * right.z + left.x * right.y - left.y * right.x,
left.w * right.w - left.x * right.x - left.y * right.y
- left.z * right.z);
return dest;
}
/**
* Sets the value of this quaternion to the quaternion product of
* quaternions left and right (this = left * right). Note that this is safe
* for aliasing (e.g. this can be left or right).
*
* @param left
* the first quaternion
* @param right
* the second quaternion
*/
public static Quaternion mul(Quaternion left, Quaternion right, Quaternion dest) {
if (dest == null) dest = new Quaternion();
dest.set(
left.x * right.w + left.w * right.x + left.y * right.z - left.z * right.y,
left.y * right.w + left.w * right.y + left.z * right.x - left.x * right.z,
left.z * right.w + left.w * right.z + left.x * right.y - left.y * right.x,
left.w * right.w - left.x * right.x - left.y * right.y - left.z * right.z);
return dest;
}
/**
*
* Multiplies quaternion left by the inverse of quaternion right and places
* the value into this quaternion. The value of both argument quaternions is
* preservered (this = left * right^-1).
*
* @param left
* the left quaternion
* @param right
* the right quaternion
*/
public static Quaternion mulInverse(Quaternion left, Quaternion right,
Quaternion dest) {
float n = right.lengthSquared();
// zero-div may occur.
n = (n == 0.0 ? n : 1 / n);
// store on stack once for aliasing-safty
if (dest == null)
dest = new Quaternion();
dest
.set((left.x * right.w - left.w * right.x - left.y
* right.z + left.z * right.y)
* n, (left.y * right.w - left.w * right.y - left.z
* right.x + left.x * right.z)
* n, (left.z * right.w - left.w * right.z - left.x
* right.y + left.y * right.x)
* n, (left.w * right.w + left.x * right.x + left.y
* right.y + left.z * right.z)
* n);
/**
*
* Multiplies quaternion left by the inverse of quaternion right and places
* the value into this quaternion. The value of both argument quaternions is
* preservered (this = left * right^-1).
*
* @param left
* the left quaternion
* @param right
* the right quaternion
*/
public static Quaternion mulInverse(Quaternion left, Quaternion right, Quaternion dest) {
float n = right.lengthSquared();
// zero-div may occur.
n = (n == 0.0 ? n : 1 / n);
// store on stack once for aliasing-safty
if (dest == null) dest = new Quaternion();
dest.set(
(left.x * right.w - left.w * right.x - left.y * right.z + left.z * right.y) * n,
(left.y * right.w - left.w * right.y - left.z * right.x + left.x * right.z) * n,
(left.z * right.w - left.w * right.z - left.x * right.y + left.y * right.x) * n,
(left.w * right.w + left.x * right.x + left.y * right.y + left.z * right.z) * n);
return dest;
}
return dest;
}
/**
* Sets the value of this quaternion to the equivalent rotation of the
* Axis-Angle argument.
*
* @param a1
* the axis-angle: (x,y,z) is the axis and w is the angle
*/
public final void setFromAxisAngle(Vector4f a1) {
x = a1.x;
y = a1.y;
z = a1.z;
float n = (float) Math.sqrt(x * x + y * y + z * z);
// zero-div may occur.
float s = (float) (Math.sin(0.5 * a1.w) / n);
x *= s;
y *= s;
z *= s;
w = (float) Math.cos(0.5 * a1.w);
}
/**
* Sets the value of this quaternion to the equivalent rotation of the
* Axis-Angle argument.
*
* @param a1
* the axis-angle: (x,y,z) is the axis and w is the angle
*/
public final void setFromAxisAngle(Vector4f a1) {
x = a1.x;
y = a1.y;
z = a1.z;
float n = (float) Math.sqrt(x * x + y * y + z * z);
// zero-div may occur.
float s = (float) (Math.sin(0.5 * a1.w) / n);
x *= s;
y *= s;
z *= s;
w = (float) Math.cos(0.5 * a1.w);
}
/**
* Sets the value of this quaternion using the rotational component of the
* passed matrix.
*
* @param m
* The matrix
* @return this
*/
public final Quaternion setFromMatrix(Matrix4f m) {
return setFromMatrix(m, this);
}
/**
* Sets the value of this quaternion using the rotational component of the
* passed matrix.
*
* @param m
* The matrix
* @return this
*/
public final Quaternion setFromMatrix(Matrix4f m) {
return setFromMatrix(m, this);
}
/**
* Sets the value of the source quaternion using the rotational component of the
* passed matrix.
*
* @param m
* The source matrix
* @param q
* The destination quaternion, or null if a new quaternion is to be created
* @return q
*/
public static Quaternion setFromMatrix(Matrix4f m, Quaternion q) {
return q.setFromMat(m.m00, m.m01, m.m02, m.m10, m.m11, m.m12, m.m20,
m.m21, m.m22);
}
/**
* Sets the value of the source quaternion using the rotational component of the
* passed matrix.
*
* @param m
* The source matrix
* @param q
* The destination quaternion, or null if a new quaternion is to be created
* @return q
*/
public static Quaternion setFromMatrix(Matrix4f m, Quaternion q) {
return q.setFromMat(m.m00, m.m01, m.m02, m.m10, m.m11, m.m12, m.m20, m.m21, m.m22);
}
/**
* Sets the value of this quaternion using the rotational component of the
* passed matrix.
*
* @param m
* The source matrix
*/
public final Quaternion setFromMatrix(Matrix3f m) {
return setFromMatrix(m, this);
}
/**
* Sets the value of this quaternion using the rotational component of the
* passed matrix.
*
* @param m
* The source matrix
*/
public final Quaternion setFromMatrix(Matrix3f m) {
return setFromMatrix(m, this);
}
/**
* Sets the value of the source quaternion using the rotational component of the
* passed matrix.
*
* @param m
* The source matrix
* @param q
* The destination quaternion, or null if a new quaternion is to be created
* @return q
*/
public static Quaternion setFromMatrix(Matrix3f m, Quaternion q) {
return q.setFromMat(m.m00, m.m01, m.m02, m.m10, m.m11, m.m12, m.m20,
m.m21, m.m22);
}
/**
* Sets the value of the source quaternion using the rotational component of the
* passed matrix.
*
* @param m
* The source matrix
* @param q
* The destination quaternion, or null if a new quaternion is to be created
* @return q
*/
public static Quaternion setFromMatrix(Matrix3f m, Quaternion q) {
return q.setFromMat(m.m00, m.m01, m.m02, m.m10, m.m11, m.m12, m.m20, m.m21, m.m22);
}
/**
* Private method to perform the matrix-to-quaternion conversion
*/
private Quaternion setFromMat(float m00, float m01, float m02, float m10,
float m11, float m12, float m20, float m21, float m22) {
/**
* Private method to perform the matrix-to-quaternion conversion
*/
private Quaternion setFromMat(
float m00, float m01, float m02, float m10, float m11, float m12, float m20, float m21, float m22) {
float s;
float tr = m00 + m11 + m22;
if (tr >= 0.0) {
s = (float) Math.sqrt(tr + 1.0);
w = s * 0.5f;
s = 0.5f / s;
x = (m21 - m12) * s;
y = (m02 - m20) * s;
z = (m10 - m01) * s;
} else {
float max = Math.max(Math.max(m00, m11), m22);
if (max == m00) {
s = (float) Math.sqrt(m00 - (m11 + m22) + 1.0);
x = s * 0.5f;
s = 0.5f / s;
y = (m01 + m10) * s;
z = (m20 + m02) * s;
w = (m21 - m12) * s;
} else if (max == m11) {
s = (float) Math.sqrt(m11 - (m22 + m00) + 1.0);
y = s * 0.5f;
s = 0.5f / s;
z = (m12 + m21) * s;
x = (m01 + m10) * s;
w = (m02 - m20) * s;
} else {
s = (float) Math.sqrt(m22 - (m00 + m11) + 1.0);
z = s * 0.5f;
s = 0.5f / s;
x = (m20 + m02) * s;
y = (m12 + m21) * s;
w = (m10 - m01) * s;
}
}
return this;
}
float s;
float tr = m00 + m11 + m22;
if (tr >= 0.0) {
s = (float) Math.sqrt(tr + 1.0);
w = s * 0.5f;
s = 0.5f / s;
x = (m21 - m12) * s;
y = (m02 - m20) * s;
z = (m10 - m01) * s;
} else {
float max = Math.max(Math.max(m00, m11), m22);
if (max == m00) {
s = (float) Math.sqrt(m00 - (m11 + m22) + 1.0);
x = s * 0.5f;
s = 0.5f / s;
y = (m01 + m10) * s;
z = (m20 + m02) * s;
w = (m21 - m12) * s;
} else if (max == m11) {
s = (float) Math.sqrt(m11 - (m22 + m00) + 1.0);
y = s * 0.5f;
s = 0.5f / s;
z = (m12 + m21) * s;
x = (m01 + m10) * s;
w = (m02 - m20) * s;
} else {
s = (float) Math.sqrt(m22 - (m00 + m11) + 1.0);
z = s * 0.5f;
s = 0.5f / s;
x = (m20 + m02) * s;
y = (m12 + m21) * s;
w = (m10 - m01) * s;
}
}
return this;
}
}
@@ -37,18 +37,18 @@ import java.nio.FloatBuffer;
* @author foo
*/
public interface ReadableVector {
/**
* @return the length of the vector
*/
float length();
/**
* @return the length squared of the vector
*/
float lengthSquared();
/**
* Store this vector in a FloatBuffer
* @param buf The buffer to store it in, at the current position
* @return this
*/
Vector store(FloatBuffer buf);
}
/**
* @return the length of the vector
*/
float length();
/**
* @return the length squared of the vector
*/
float lengthSquared();
/**
* Store this vector in a FloatBuffer
* @param buf The buffer to store it in, at the current position
* @return this
*/
Vector store(FloatBuffer buf);
}
Loaded 100 of 110 files, more files were not shown because too many files have changed in this diff. Show more