在 Java 中加载 OpenGL 和 LWJGL3 中的纹理

Load a texture within OpenGL and LWJGL3 in Java

我正在学习有关在屏幕上呈现文本的教程,但我似乎找不到加载字体纹理的有效方法。我尝试了 slick 库,但它已经过时了:它使用 lwjgl2 的方法,在 lwjgl3 中不再存在,所以它抛出一个 java.lang.NoSuchMethodError。在网上我发现glfw(集成在lwjgl中)有一个方法叫做glfwLoadTexture2D,但看起来它只在glfw的C++版本中可用。我还在 openGL utils 中找到了一个名为 gluBuild2DMipmaps 的方法,但它看起来不像 lwjgl 有它: 类 GLUtilGLUtils 存在,但它们不存在有没有类似的方法,真的是几乎空白

我正在寻找加载纹理并返回纹理 ID 以供进一步使用的东西,可能不需要使用外部库。

LWJGL3 没有像以前的 slick 那样随时可用的纹理加载功能。但是你可以很容易地使用 png 图像,你所需要的只是 PNGLoader 你可以在这里找到它:https://mvnrepository.com/artifact/org.l33tlabs.twl/pngdecoder/1.0

(Slicks PNG 解码器也基于它)

一种功能齐全的使用方法

public static Texture loadTexture(String fileName){

    //load png file
    PNGDecoder decoder = new PNGDecoder(ClassName.class.getResourceAsStream(fileName));

    //create a byte buffer big enough to store RGBA values
    ByteBuffer buffer = ByteBuffer.allocateDirect(4 * decoder.getWidth() * decoder.getHeight());

    //decode
    decoder.decode(buffer, decoder.getWidth() * 4, PNGDecoder.Format.RGBA);

    //flip the buffer so its ready to read
    buffer.flip();

    //create a texture
    int id = glGenTextures();

    //bind the texture
    glBindTexture(GL_TEXTURE_2D, id);

    //tell opengl how to unpack bytes
    glPixelStorei(GL_UNPACK_ALIGNMENT, 1);

    //set the texture parameters, can be GL_LINEAR or GL_NEAREST
    glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
    glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);

    //upload texture
    glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, decoder.getWidth(), decoder.getHeight(), 0, GL_RGBA, GL_UNSIGNED_BYTE, buffer);

    // Generate Mip Map
    glGenerateMipmap(GL_TEXTURE_2D);

    return new Texture(id); 
}

此方法假定一个简单的纹理 class,例如:

public class Texture{

    private int id;

    public Texture(int id){
        this.id = id;
    }

    public int getId(){
        return id;
    }
}

如果您想要宽度,高度字段 decoder.getWidth() decoder.getHeight() 将 returns 给您。

最后你创建了一个像这样的纹理:

Texture texture = ClassName.loadTexture("/textures/texture.png");

texture.getId();

会给你相应的贴图id。