/** Optional, throws GLException if not available in profile */ public final int gluScaleImage( int format, int widthin, int heightin, int typein, java.nio.Buffer datain, int widthout, int heightout, int typeout, java.nio.Buffer dataout) { validateMipmap(); java.nio.ByteBuffer in = null; java.nio.ByteBuffer out = null; in = copyToByteBuffer(datain); if (dataout instanceof java.nio.ByteBuffer) { out = (java.nio.ByteBuffer) dataout; } else if (dataout instanceof java.nio.ShortBuffer) { out = Buffers.newDirectByteBuffer(dataout.remaining() * Buffers.SIZEOF_SHORT); } else if (dataout instanceof java.nio.IntBuffer) { out = Buffers.newDirectByteBuffer(dataout.remaining() * Buffers.SIZEOF_INT); } else if (dataout instanceof java.nio.FloatBuffer) { out = Buffers.newDirectByteBuffer(dataout.remaining() * Buffers.SIZEOF_FLOAT); } else { throw new IllegalArgumentException( "Unsupported destination buffer type (must be byte, short, int, or float)"); } int errno = Mipmap.gluScaleImage( getCurrentGL2ES1(), format, widthin, heightin, typein, in, widthout, heightout, typeout, out); if (errno == 0) { out.rewind(); if (out != dataout) { if (dataout instanceof java.nio.ShortBuffer) { ((java.nio.ShortBuffer) dataout).put(out.asShortBuffer()); } else if (dataout instanceof java.nio.IntBuffer) { ((java.nio.IntBuffer) dataout).put(out.asIntBuffer()); } else if (dataout instanceof java.nio.FloatBuffer) { ((java.nio.FloatBuffer) dataout).put(out.asFloatBuffer()); } else { throw new RuntimeException("Should not reach here"); } } } return (errno); }
private static boolean initByteOrder() { ByteBuffer tst_b = Buffers.newDirectByteBuffer(Buffers.SIZEOF_INT); // 32bit in native order IntBuffer tst_i = tst_b.asIntBuffer(); ShortBuffer tst_s = tst_b.asShortBuffer(); tst_i.put(0, 0x0A0B0C0D); return 0x0C0D == tst_s.get(0); }
@Override public final ColorSpace allocate( int width, int height, ColorSpace sourceCM, int sourceComponents) throws RuntimeException { this.width = width; this.height = height; this.sourceComponents = sourceComponents; this.sourceCS = sourceCM; this.data = Buffers.newDirectByteBuffer(width * height * storageComponents); return storageCS; }
public OpenALAudioDevice( OpenALAudio audio, int sampleRate, boolean isMono, int bufferSize, int bufferCount) { this.audio = audio; channels = isMono ? 1 : 2; this.bufferSize = bufferSize; this.bufferCount = bufferCount; this.format = channels > 1 ? ALConstants.AL_FORMAT_STEREO16 : ALConstants.AL_FORMAT_MONO16; this.sampleRate = sampleRate; secondsPerBuffer = (float) bufferSize / bytesPerSample / channels / sampleRate; tempBuffer = Buffers.newDirectByteBuffer(bufferSize); }
@Test public void bufferWithHostPointerTest() { out.println(" - - - highLevelTest; host pointer test - - - "); final int elements = NUM_ELEMENTS; final CLContext context = CLContext.create(); final ByteBuffer buffer = Buffers.newDirectByteBuffer(elements * SIZEOF_INT); // fill only first read buffer -> we will copy the payload to the second later. fillBuffer(buffer, 12345); final CLCommandQueue queue = context.getDevices()[0].createCommandQueue(); final Mem[] bufferConfig = new Mem[] {Mem.COPY_BUFFER, Mem.USE_BUFFER}; for (int i = 0; i < bufferConfig.length; i++) { out.println("testing with " + bufferConfig[i] + " config"); final CLBuffer<ByteBuffer> clBufferA = context.createBuffer(buffer, Mem.READ_ONLY, bufferConfig[i]); final CLBuffer<ByteBuffer> clBufferB = context.createByteBuffer(elements * SIZEOF_INT, Mem.READ_ONLY); // asynchronous write of data to GPU device, blocking read later to get the computed results // back. queue .putCopyBuffer(clBufferA, clBufferB, clBufferA.buffer.capacity()) // copy A -> B .putReadBuffer(clBufferB, true) // read B .finish(); assertEquals(2, context.getMemoryObjects().size()); clBufferA.release(); assertEquals(1, context.getMemoryObjects().size()); clBufferB.release(); assertEquals(0, context.getMemoryObjects().size()); // uploading worked when a==b. out.println("validating computed results..."); checkIfEqual(clBufferA.buffer, clBufferB.buffer, elements); out.println("results are valid"); } context.release(); }
private int checkSelection(GL2ES2 gl, int x, int y, int width, int height) { gl.glPixelStorei(GL2ES2.GL_PACK_ALIGNMENT, 4); gl.glPixelStorei(GL2ES2.GL_UNPACK_ALIGNMENT, 4); gl.glClearColor(sceneClearColor[0], sceneClearColor[1], sceneClearColor[2], sceneClearColor[3]); gl.glClear(GL.GL_COLOR_BUFFER_BIT | GL.GL_DEPTH_BUFFER_BIT); render(gl, width, height, 0, null, true); ByteBuffer pixel = Buffers.newDirectByteBuffer(4); pixel.order(ByteOrder.nativeOrder()); IntBuffer viewport = IntBuffer.allocate(4); gl.glGetIntegerv(GL2ES2.GL_VIEWPORT, viewport); gl.glReadPixels(x, viewport.get(3) - y, 1, 1, GL2ES2.GL_RGBA, GL2ES2.GL_UNSIGNED_BYTE, pixel); int qp = pixel.get(0) & 0xFF; int index = Math.round(((qp / 255.0f) * (count + 2)) - 1); if (index < 0 || index >= count) return -1; return index; }
public static PixelRectangle convert( final PixelRectangle src, final PixelFormat destFmt, final int ddestStride, final boolean isGLOriented, final boolean destIsDirect) { final int width = src.getSize().getWidth(); final int height = src.getSize().getHeight(); final int bpp = destFmt.comp.bytesPerPixel(); final int destStride; if (0 != ddestStride) { destStride = ddestStride; } else { destStride = bpp * width; } final int capacity = destStride * height; final ByteBuffer destBB = destIsDirect ? Buffers.newDirectByteBuffer(capacity) : ByteBuffer.allocate(capacity).order(src.getPixels().order()); convert(src, destBB, destFmt, isGLOriented, destStride); return new PixelRectangle.GenericPixelRect( destFmt, src.getSize(), destStride, isGLOriented, destBB); }
public void load(boolean IA16, int textureBitDepth, ByteBuffer tmem, GL2 gl) { int glInternalFormat; int glType; ImageFormat.GetTexelFunc GetTexel; if (((ImageFormat.imageFormat[size][format].autoFormat == GL2.GL_RGBA8) || ((format == TextureCache.G_IM_FMT_CI) && (IA16)) || (textureBitDepth == 2)) && (textureBitDepth != 0)) { textureBytes = (realWidth * realHeight) << 2; if ((format == TextureCache.G_IM_FMT_CI) && (IA16)) { if (size == TextureCache.G_IM_SIZ_4b) GetTexel = ImageFormat.GetCI4IA_RGBA8888; else GetTexel = ImageFormat.GetCI8IA_RGBA8888; glInternalFormat = GL2.GL_RGBA8; glType = GL2.GL_UNSIGNED_BYTE; } else { GetTexel = ImageFormat.imageFormat[size][format].Get32; glInternalFormat = ImageFormat.imageFormat[size][format].glInternalFormat32; glType = ImageFormat.imageFormat[size][format].glType32; } } else { textureBytes = (realWidth * realHeight) << 1; if ((format == TextureCache.G_IM_FMT_CI) && (IA16)) { if (size == TextureCache.G_IM_SIZ_4b) GetTexel = ImageFormat.GetCI4IA_RGBA4444; else GetTexel = ImageFormat.GetCI8IA_RGBA4444; glInternalFormat = GL2.GL_RGBA4; glType = GL2.GL_UNSIGNED_SHORT_4_4_4_4; } else { GetTexel = ImageFormat.imageFormat[size][format].Get16; glInternalFormat = ImageFormat.imageFormat[size][format].glInternalFormat16; glType = ImageFormat.imageFormat[size][format].glType16; } } ByteBuffer dest = Buffers.newDirectByteBuffer(textureBytes); int newline = line; int mirrorSBit; int maskSMask; int clampSClamp; int mirrorTBit; int maskTMask; int clampTClamp; if (size == TextureCache.G_IM_SIZ_32b) newline <<= 1; if (maskS != 0) { clampSClamp = clampS != 0 ? clampWidth - 1 : (mirrorS != 0 ? (width << 1) - 1 : width - 1); maskSMask = (1 << maskS) - 1; mirrorSBit = mirrorS != 0 ? 1 << maskS : 0; } else { clampSClamp = StrictMath.min(clampWidth, width) - 1; maskSMask = 0xFFFF; mirrorSBit = 0x0000; } if (maskT != 0) { clampTClamp = clampT != 0 ? clampHeight - 1 : (mirrorT != 0 ? (height << 1) - 1 : height - 1); maskTMask = (1 << maskT) - 1; mirrorTBit = mirrorT != 0 ? 1 << maskT : 0; } else { clampTClamp = StrictMath.min(clampHeight, height) - 1; maskTMask = 0xFFFF; mirrorTBit = 0x0000; } ByteBuffer src; int i; int j = 0; int tx; int ty; for (int y = 0; y < realHeight; y++) { ty = StrictMath.min(y, clampTClamp) & maskTMask; if ((y & mirrorTBit) != 0) ty ^= maskTMask; tmem.position((tMem + (newline * ty)) * 8); src = tmem.slice(); i = (ty & 1) << 1; for (int x = 0; x < realWidth; x++) { tx = StrictMath.min(x, clampSClamp) & maskSMask; if ((x & mirrorSBit) != 0) tx ^= maskSMask; if (glInternalFormat == GL2.GL_RGBA8) { dest.asIntBuffer().put(j++, GetTexel.GetTexel(src, tx, i, palette)); } else { dest.asShortBuffer().put(j++, (short) GetTexel.GetTexel(src, tx, i, palette)); } } } gl.glTexImage2D( GL2.GL_TEXTURE_2D, 0, glInternalFormat, realWidth, realHeight, 0, GL2.GL_RGBA, glType, dest); }
/** * Creates an instance of PMVMatrix. * * @param useBackingArray <code>true</code> for non direct NIO Buffers with guaranteed backing * array, which allows faster access in Java computation. * <p><code>false</code> for direct NIO buffers w/o a guaranteed backing array. In most Java * implementations, direct NIO buffers have no backing array and hence the Java computation * will be throttled down by direct IO get/put operations. * <p>Depending on the application, ie. whether the Java computation or JNI invocation and * hence native data transfer part is heavier, this flag shall be set to <code>true</code> or * <code>false</code>. */ public PMVMatrix(boolean useBackingArray) { this.usesBackingArray = useBackingArray; // I Identity // T Texture // P Projection // Mv ModelView // Mvi Modelview-Inverse // Mvit Modelview-Inverse-Transpose if (useBackingArray) { matrixBufferArray = new float[6 * 16 + ProjectFloat.getRequiredFloatBufferSize()]; matrixBuffer = null; } else { matrixBufferArray = null; matrixBuffer = Buffers.newDirectByteBuffer( (6 * 16 + ProjectFloat.getRequiredFloatBufferSize()) * Buffers.SIZEOF_FLOAT); matrixBuffer.mark(); } matrixIdent = Buffers.slice2Float(matrixBuffer, matrixBufferArray, 0 * 16, 1 * 16); // I matrixTex = Buffers.slice2Float(matrixBuffer, matrixBufferArray, 1 * 16, 1 * 16); // T matrixPMvMvit = Buffers.slice2Float( matrixBuffer, matrixBufferArray, 2 * 16, 4 * 16); // P + Mv + Mvi + Mvit matrixPMvMvi = Buffers.slice2Float( matrixBuffer, matrixBufferArray, 2 * 16, 3 * 16); // P + Mv + Mvi matrixPMv = Buffers.slice2Float(matrixBuffer, matrixBufferArray, 2 * 16, 2 * 16); // P + Mv matrixP = Buffers.slice2Float(matrixBuffer, matrixBufferArray, 2 * 16, 1 * 16); // P matrixMv = Buffers.slice2Float(matrixBuffer, matrixBufferArray, 3 * 16, 1 * 16); // Mv matrixMvi = Buffers.slice2Float( matrixBuffer, matrixBufferArray, 4 * 16, 1 * 16); // Mvi matrixMvit = Buffers.slice2Float( matrixBuffer, matrixBufferArray, 5 * 16, 1 * 16); // Mvit projectFloat = new ProjectFloat(matrixBuffer, matrixBufferArray, 6 * 16); if (null != matrixBuffer) { matrixBuffer.reset(); } FloatUtil.makeIdentityf(matrixIdent); vec3f = new float[3]; matrixMult = new float[16]; matrixTrans = new float[16]; matrixRot = new float[16]; matrixScale = new float[16]; matrixOrtho = new float[16]; matrixFrustum = new float[16]; FloatUtil.makeIdentityf(matrixTrans, 0); FloatUtil.makeIdentityf(matrixRot, 0); FloatUtil.makeIdentityf(matrixScale, 0); FloatUtil.makeIdentityf(matrixOrtho, 0); FloatUtil.makeZero(matrixFrustum, 0); matrixPStack = new ArrayList<float[]>(); matrixMvStack = new ArrayList<float[]>(); // default values and mode glMatrixMode(GL_PROJECTION); glLoadIdentity(); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); glMatrixMode(GL.GL_TEXTURE); glLoadIdentity(); setDirty(); update(); }
DemoGL2ES1Plain(final boolean useArrayData, final boolean useVBO) { this.useArrayData = useArrayData; this.useVBO = useVBO; this.glu = new GLUgl2es1(); bufferAll = Buffers.newDirectByteBuffer((colors.length + vertices.length) * Buffers.SIZEOF_FLOAT); bufferVOffset = 0; bufferVSize = 3 * 3 * GLBuffers.sizeOfGLType(GL.GL_FLOAT); bufferCOffset = bufferVSize; bufferCSize = 3 * 3 * GLBuffers.sizeOfGLType(GL.GL_FLOAT); bufferV = (FloatBuffer) GLBuffers.sliceGLBuffer(bufferAll, bufferVOffset, bufferVSize, GL.GL_FLOAT); bufferV.put(vertices, 0, vertices.length).rewind(); bufferC = (FloatBuffer) GLBuffers.sliceGLBuffer(bufferAll, bufferCOffset, bufferCSize, GL.GL_FLOAT); bufferC.put(colors, 0, colors.length).rewind(); System.err.println( "bufferAll: " + bufferAll + ", byteOffset " + Buffers.getDirectBufferByteOffset(bufferAll)); System.err.println( "bufferV: off " + bufferVOffset + ", size " + bufferVSize + ": " + bufferV + ", byteOffset " + Buffers.getDirectBufferByteOffset(bufferV)); System.err.println( "bufferC: off " + bufferCOffset + ", size " + bufferCSize + ": " + bufferC + ", byteOffset " + Buffers.getDirectBufferByteOffset(bufferC)); if (useArrayData) { arrayV = GLArrayDataWrapper.createFixed( GLPointerFunc.GL_VERTEX_ARRAY, 3, GL.GL_FLOAT, false, 0, bufferV, 0, bufferVOffset, GL.GL_STATIC_DRAW, GL.GL_ARRAY_BUFFER); arrayC = GLArrayDataWrapper.createFixed( GLPointerFunc.GL_COLOR_ARRAY, 3, GL.GL_FLOAT, false, 0, bufferC, 0, bufferCOffset, GL.GL_STATIC_DRAW, GL.GL_ARRAY_BUFFER); } else { arrayV = null; arrayC = null; } }
/** * This program draws a texture mapped teapot with automatically generated texture coordinates. The * texture is rendered as stripes on the teapot. Initially, the object is drawn with texture * coordinates based upon the object coordinates of the vertex and distance from the plane x = 0. * Pressing the 'e' key changes the coordinate generation to eye coordinates of the vertex. Pressing * the 'o' key switches it back to the object coordinates. Pressing the 's' key changes the plane to * a slanted one (x + y + z = 0). Pressing the 'x' key switches it back to x = 0. * * @author Kiet Le (Java port) Ported to JOGL 2.x by Claudio Eduardo Goes */ public class texgen // extends GLSkeleton<GLJPanel> implements GLEventListener, KeyListener { private GLUT glut; private static final int stripeImageWidth = 32; private byte stripeImage[] = new byte[3 * stripeImageWidth]; private ByteBuffer stripeImageBuf = Buffers.newDirectByteBuffer(stripeImage.length); /* glTexGen stuff: */ // private float sgenparams[] = { 1.0f, 1.0f, 1.0f, 0.0f }; private int texName[] = new int[1]; private static double xequalzero[] = {1.0, 0.0, 0.0, 0.0}; private static double slanted[] = {1.0, 1.0, 1.0, 0.0}; private static double currentCoeff[]; private static int currentPlane; private static int currentGenMode; @Override protected GLJPanel createDrawable() { GLCapabilities caps = new GLCapabilities(null); caps.setSampleBuffers(true); // enable sample buffers for aliasing caps.setNumSamples(2); // GLJPanel panel = new GLJPanel(caps); panel.addGLEventListener(this); panel.addKeyListener(this); return panel; } public static void main(String[] args) { texgen demo = new texgen(); JFrame.setDefaultLookAndFeelDecorated(true); JFrame frame = new JFrame("texgen"); frame.setSize(400, 400); frame.setLocationRelativeTo(null); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.getContentPane().add(demo.drawable); frame.setVisible(true); demo.drawable.requestFocusInWindow(); } public void init(GLAutoDrawable drawable) { GL2 gl = drawable.getGL().getGL2(); glut = new GLUT(); // gl.glClearColor(0.0f, 0.0f, 0.0f, 0.0f); makeStripeImage(); gl.glPixelStorei(GL.GL_UNPACK_ALIGNMENT, 1); gl.glGenTextures(1, texName, 0); gl.glBindTexture(GL2.GL_TEXTURE_1D, texName[0]); gl.glTexParameterf(GL2.GL_TEXTURE_1D, GL2.GL_TEXTURE_WRAP_S, GL2.GL_REPEAT); gl.glTexParameterf( GL2.GL_TEXTURE_1D, // GL2.GL_TEXTURE_MAG_FILTER, GL.GL_LINEAR); gl.glTexParameterf( GL2.GL_TEXTURE_1D, // GL2.GL_TEXTURE_MIN_FILTER, GL.GL_LINEAR); gl.glTexImage1D( GL2.GL_TEXTURE_1D, 0, GL2.GL_RGBA, stripeImageWidth, // 0, GL2.GL_RGB, GL.GL_UNSIGNED_BYTE, stripeImageBuf); gl.glTexEnvf(GL2.GL_TEXTURE_ENV, GL2.GL_TEXTURE_ENV_MODE, GL2.GL_MODULATE); currentCoeff = xequalzero; currentGenMode = GL2.GL_OBJECT_LINEAR; currentPlane = GL2.GL_OBJECT_PLANE; gl.glTexGeni(GL2.GL_S, GL2.GL_TEXTURE_GEN_MODE, GL2.GL_OBJECT_LINEAR); gl.glTexGendv(GL2.GL_S, GL2.GL_OBJECT_PLANE, currentCoeff, 0); // gl.glEnable(GL.GL_DEPTH_TEST); gl.glDepthFunc(GL.GL_LESS); gl.glEnable(GL2.GL_TEXTURE_GEN_S); gl.glEnable(GL2.GL_TEXTURE_1D); gl.glEnable(GL.GL_CULL_FACE); gl.glEnable(GL2.GL_LIGHTING); gl.glEnable(GL2.GL_LIGHT0); gl.glEnable(GL2.GL_AUTO_NORMAL); gl.glEnable(GL2.GL_NORMALIZE); gl.glFrontFace(GL.GL_CW); gl.glCullFace(GL.GL_BACK); gl.glMaterialf(GL.GL_FRONT, GL2.GL_SHININESS, 64.0f); } public void display(GLAutoDrawable drawable) { GL2 gl = drawable.getGL().getGL2(); // gl.glClear(GL.GL_COLOR_BUFFER_BIT | GL.GL_DEPTH_BUFFER_BIT); gl.glPushMatrix(); gl.glRotatef(45.0f, 0.0f, 0.0f, 1.0f); gl.glTexGeni(GL2.GL_S, GL2.GL_TEXTURE_GEN_MODE, currentGenMode); gl.glTexGendv(GL2.GL_S, currentPlane, currentCoeff, 0); gl.glBindTexture(GL2.GL_TEXTURE_1D, texName[0]); glut.glutSolidTeapot(2.0f); gl.glPopMatrix(); gl.glFlush(); } public void reshape(GLAutoDrawable drawable, int x, int y, int w, int h) { GL2 gl = drawable.getGL().getGL2(); // gl.glViewport(0, 0, w, h); gl.glMatrixMode(GL2.GL_PROJECTION); gl.glLoadIdentity(); if (w <= h) gl.glOrtho(-3.5, 3.5, -3.5 * (float) h / (float) w, 3.5 * (float) h / (float) w, -3.5, 3.5); else gl.glOrtho( -3.5 * (float) w / (float) h, // 3.5 * (float) w / (float) h, -3.5, 3.5, -3.5, 3.5); gl.glMatrixMode(GL2.GL_MODELVIEW); gl.glLoadIdentity(); } public void displayChanged(GLAutoDrawable drawable, boolean modeChanged, boolean deviceChanged) {} private void makeStripeImage() { for (int j = 0; j < stripeImageWidth; j++) { // stripeImage[3 * j] = (j <= 4) ? 255 : 0; // stripeImage[3 * j + 1] = (j > 4) ? 255 : 0; // stripeImage[3 * j + 2] = 0; stripeImageBuf.put(((j <= 4) ? (byte) 255 : (byte) 0)); stripeImageBuf.put(((j > 4) ? (byte) 255 : (byte) 0)); stripeImageBuf.put((byte) 0); } stripeImageBuf.rewind(); } public void keyTyped(KeyEvent key) {} public void keyPressed(KeyEvent key) { switch (key.getKeyChar()) { case KeyEvent.VK_ESCAPE: System.exit(0); break; case 'e': case 'E': currentGenMode = GL2.GL_EYE_LINEAR; currentPlane = GL2.GL_EYE_PLANE; break; case 'o': case 'O': currentGenMode = GL2.GL_OBJECT_LINEAR; currentPlane = GL2.GL_OBJECT_PLANE; break; case 's': case 'S': currentCoeff = slanted; break; case 'x': case 'X': currentCoeff = xequalzero; break; default: break; } super.refresh(); } public void keyReleased(KeyEvent key) {} public void dispose(GLAutoDrawable arg0) {} }
public static int gluScaleImage( GL gl, int format, int widthin, int heightin, int typein, ByteBuffer datain, int widthout, int heightout, int typeout, ByteBuffer dataout) { int datainPos = datain.position(); int dataoutPos = dataout.position(); try { int components; ByteBuffer beforeimage; ByteBuffer afterimage; PixelStorageModes psm = new PixelStorageModes(); if ((widthin == 0) || (heightin == 0) || (widthout == 0) || (heightout == 0)) { return (0); } if ((widthin < 0) || (heightin < 0) || (widthout < 0) || (heightout < 0)) { return (GLU.GLU_INVALID_VALUE); } if (!legalFormat(format) || !legalType(typein) || !legalType(typeout)) { return (GLU.GLU_INVALID_ENUM); } if (!isLegalFormatForPackedPixelType(format, typein)) { return (GLU.GLU_INVALID_OPERATION); } if (!isLegalFormatForPackedPixelType(format, typeout)) { return (GLU.GLU_INVALID_OPERATION); } beforeimage = Buffers.newDirectByteBuffer( image_size(widthin, heightin, format, GL2GL3.GL_UNSIGNED_SHORT)); afterimage = Buffers.newDirectByteBuffer( image_size(widthout, heightout, format, GL2GL3.GL_UNSIGNED_SHORT)); if (beforeimage == null || afterimage == null) { return (GLU.GLU_OUT_OF_MEMORY); } retrieveStoreModes(gl, psm); Image.fill_image( psm, widthin, heightin, format, typein, is_index(format), datain, beforeimage.asShortBuffer()); components = elements_per_group(format, 0); ScaleInternal.scale_internal( components, widthin, heightin, beforeimage.asShortBuffer(), widthout, heightout, afterimage.asShortBuffer()); Image.empty_image( psm, widthout, heightout, format, typeout, is_index(format), afterimage.asShortBuffer(), dataout); return (0); } finally { datain.position(datainPos); dataout.position(dataoutPos); } }
private PNGImage(InputStream in) { final PngReader pngr = new PngReader(new BufferedInputStream(in), null); final ImageInfo imgInfo = pngr.imgInfo; final PngChunkPLTE plte = pngr.getMetadata().getPLTE(); final PngChunkTRNS trns = pngr.getMetadata().getTRNS(); final boolean indexed = imgInfo.indexed; final boolean hasAlpha = indexed ? (trns != null) : imgInfo.alpha; final int channels = indexed ? (hasAlpha ? 4 : 3) : imgInfo.channels; if (!(1 == channels || 3 == channels || 4 == channels)) { throw new RuntimeException( "PNGImage can only handle Lum/RGB/RGBA [1/3/4 channels] images for now. Channels " + channels + " Paletted: " + indexed); } bytesPerPixel = indexed ? channels : imgInfo.bytesPixel; if (!(1 == bytesPerPixel || 3 == bytesPerPixel || 4 == bytesPerPixel)) { throw new RuntimeException( "PNGImage can only handle Lum/RGB/RGBA [1/3/4 bpp] images for now. BytesPerPixel " + bytesPerPixel); } if (channels != bytesPerPixel) { throw new RuntimeException( "PNGImage currently only handles Channels [1/3/4] == BytePerPixel [1/3/4], channels: " + channels + ", bytesPerPixel " + bytesPerPixel); } pixelWidth = imgInfo.cols; pixelHeight = imgInfo.rows; dpi = new double[2]; { final double[] dpi2 = pngr.getMetadata().getDpi(); dpi[0] = dpi2[0]; dpi[1] = dpi2[1]; } if (indexed) { if (hasAlpha) { glFormat = GL.GL_RGBA; } else { glFormat = GL.GL_RGB; } } else { switch (channels) { case 1: glFormat = GL.GL_LUMINANCE; break; case 3: glFormat = GL.GL_RGB; break; case 4: glFormat = GL.GL_RGBA; break; default: throw new InternalError( "XXX: channels: " + channels + ", bytesPerPixel " + bytesPerPixel); } } if (DEBUG) { System.err.println("PNGImage: " + imgInfo); System.err.println( "PNGImage: indexed " + indexed + ", alpha " + hasAlpha + ", channels " + channels + "/" + imgInfo.channels + ", bytesPerPixel " + bytesPerPixel + "/" + imgInfo.bytesPixel + ", pixels " + pixelWidth + "x" + pixelHeight + ", dpi " + dpi[0] + "x" + dpi[1] + ", glFormat 0x" + Integer.toHexString(glFormat)); } data = Buffers.newDirectByteBuffer(bytesPerPixel * pixelWidth * pixelHeight); reversedChannels = false; // RGB[A] isGLOriented = true; int dataOff = bytesPerPixel * pixelWidth * pixelHeight - 1; // start at end-of-buffer, reverse store int[] rgbaScanline = indexed ? new int[imgInfo.cols * channels] : null; for (int row = 0; row < pixelHeight; row++) { final ImageLine l1 = pngr.readRow(row); int lineOff = (pixelWidth - 1) * bytesPerPixel; // start w/ last pixel in line, reverse read (PNG top-left -> OpenGL // bottom-left origin) if (indexed) { for (int j = pixelWidth - 1; j >= 0; j--) { rgbaScanline = ImageLineHelper.palette2rgb( l1, plte, trns, rgbaScanline); // reuse rgbaScanline and update if resized dataOff = getPixelRGBA8(data, dataOff, rgbaScanline, lineOff, hasAlpha); lineOff -= bytesPerPixel; } } else if (1 == channels) { for (int j = pixelWidth - 1; j >= 0; j--) { data.put(dataOff--, (byte) l1.scanline[lineOff--]); // Luminance, 1 bytesPerPixel } } else { for (int j = pixelWidth - 1; j >= 0; j--) { dataOff = getPixelRGBA8(data, dataOff, l1.scanline, lineOff, hasAlpha); lineOff -= bytesPerPixel; } } } pngr.end(); }
public ByteBuffer createBuffer(int length, int elementSize) { return Buffers.newDirectByteBuffer(length * elementSize * getBytesPerElement()); }