Reputation: 1793
so I'm trying to add TrueTypeFonts to my game. And basically, I've got it to read a TrueTypeFont from a file, and it correctly reads it to a BufferedImage. But when I pass the BufferedImage to my Sprite
constructor (for loading images to be used with OpenGL), it completely breaks it. Have a look at the following images:
So here's the constructor for my Sprite utility class, which will take the BufferedImage and convert it to a ByteBuffer and bind it to an ID.
public Sprite(BufferedImage img) {
// this will show the BufferedIamge in a modal dialog, see Fig. 2
JOptionPane.showMessageDialog(null, null, "Another", JOptionPane.YES_NO_OPTION, new ImageIcon(img.getScaledInstance(img.getWidth() * 4, img.getHeight() * 4, Image.SCALE_REPLICATE)));
int[] pixels = new int[img.getWidth() * img.getHeight()];
img.getRGB(0, 0, img.getWidth(), img.getHeight(), pixels, 0, img.getWidth());
this.width = img.getWidth();
this.height = img.getHeight();
ByteBuffer buff = BufferUtils.createByteBuffer(img.getWidth() * img.getHeight() * 4);
for (int x = 0; x < img.getWidth(); x++) {
for (int y = 0; y < img.getHeight(); y++) {
int pixel = pixels[y * img.getWidth() + x];
buff.put((byte) ((pixel >> 16) & 0xFF));
buff.put((byte) ((pixel >> 8) & 0xFF));
buff.put((byte) (pixel & 0xFF));
buff.put((byte) ((pixel >> 24) & 0xFF));
}
}
buff.flip();
id = GL.glGenTextures();
GL.glEnable(GL_TEXTURE_2D);
GL.glBindTexture(GL_TEXTURE_2D, id);
GL.glPixelStorei(GL.GL_UNPACK_ALIGNMENT, 1);
GL.glPixelStorei(GL.GL_PACK_ALIGNMENT, 1);
GL.glTexImage2D(GL_TEXTURE_2D, 0, GL.GL_RGBA, width, height, 0, GL_RGBA, GL.GL_UNSIGNED_BYTE, buff);
}
Fig. 2 - The Image that we pass through, looks good!
Fig. 3 - When I render the image, note I can render any other image and it turns out ok. Even transparent ones, too.
Ignore the blob at the bottom, that's me trying to render a string of text!
Any help greatly appreciated, I've spent a while trying to suss out how to implement fonts.
Upvotes: 1
Views: 75
Reputation: 5373
Without actually running a test project, I would suspect that the reason that it looks like this is that the following code:
for (int x = 0; x < img.getWidth(); x++) {
for (int y = 0; y < img.getHeight(); y++) {
causes the pixels to be added by scanning down first and not across. To go across, flip the for loops:
for (int y = 0; y < img.getHeight(); y++) {
for (int x = 0; x < img.getWidth(); x++) {
Upvotes: 2