ByteBuffer

Howzit

The way I see that OpenGL and LWJGL loads textures and the like is with a ByteBuffer or any of the variants.

How do you populate those buffers? I know that you have to get the pixels, but what is an effiecient way for getting the pixels?

I’ve seen some methods but they don’t work very well.
How do the big game developers do it? Such as Puppy.

Shot

One way you can get the data is by retrieving the data from the Image’s Raster. (be aware that this is using the java.awt package)

For example, assuming you have an Image called “sample”


        ByteBuffer scratch = ByteBuffer.allocateDirect(4 * sample.getWidth() * sample.getHeight());
        byte data[] = (byte[]) sample.getRaster().getDataElements(0, 0, sample.getWidth(), sample.getHeight(), null);
        scratch.clear();
        scratch.put(data);
        scratch.rewind();

One thing I always get wrong with nio is forgetting the rewind before using it.

Ok.

Are you using an Image or BufferedImage, because Image does not have a method called getRaster().

I used a similar method a while ago to set my cursor and the image came out all choppy.
How do you use the normal cursor?

Shot

I haven’t done much with the mouse yet, but for textures, I usually make a new BufferedImage of type TYPE_4BYTE_ABGR and write my image into it. Then I use the aforementioned means to get the data from the new BufferedImage.

eg:


        BufferedImage sample = new BufferedImage(myImage.getWidth(null), myImage.getHeight(null), BufferedImage.TYPE_4BYTE_ABGR);

        Graphics2D g = (Graphics2D) sample.getGraphics();
        g.drawImage(myImage, null, null);
        g.dispose();