java - 使用 org.lwjgl.stb 加载纹理
问题描述
我正在尝试加载一个简单的纹理并将其应用于矩形,但它似乎不起作用。这是 org.lwjgl.stb/文件加载的错误吗(我对 opengl 不是很有经验):
这是我的 main.java 中的代码:
float vertices[] = {
// positions // colors // texture coords
0.5f, 0.5f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f, 1.0f, // top right
0.5f, -0.5f, 0.0f, 0.0f, 1.0f, 0.0f, 1.0f, 0.0f, // bottom right
-0.5f, -0.5f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, // bottom left
-0.5f, 0.5f, 0.0f, 1.0f, 1.0f, 0.0f, 0.0f, 1.0f // top left
};
int indices[] = {
0, 1, 3, // first triangle
1, 2, 3 // second triangle
};
int VBO = glGenBuffers(), VAO = glGenVertexArrays(), EBO = glGenBuffers();
glBindVertexArray(VAO);
glBindBuffer(GL_ARRAY_BUFFER, VBO);
glBufferData(GL_ARRAY_BUFFER, vertices, GL_STATIC_DRAW);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, EBO);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, indices, GL_STATIC_DRAW);
// position attribute
glVertexAttribPointer(0, 3, GL_FLOAT, false, 8*4, 0);
glEnableVertexAttribArray(0);
// color attribute
glVertexAttribPointer(1, 3, GL_FLOAT, false, 8*4, 2*4);
glEnableVertexAttribArray(1);
// texture coord attribute
glVertexAttribPointer(2, 2, GL_FLOAT, false, 8*4, 6*4);
glEnableVertexAttribArray(2);
int texture = glGenTextures();
glBindTexture(GL_TEXTURE_2D, texture);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
int[] width = new int[1], height = new int[1], nrChannels = new int[1];
ByteBuffer data = stbi_load("C:/Users/Lion/Images/biene.png", width, height, nrChannels, 0);
if(data.hasRemaining()) System.out.println(data);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, width[0], height[0], 0, GL_RGB, GL_UNSIGNED_BYTE, data);
glGenerateMipmap(GL_TEXTURE_2D);
while (!glfwWindowShouldClose(window))
{
glClear(GL_COLOR_BUFFER_BIT);
if(mainProgram != null) {
mainProgram.use();
}
glBindVertexArray(VAO);
glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_INT, 0);
这是我的顶点着色器的代码:
#version 330 core
layout (location = 0) in vec3 aPos;
layout(location = 1) in vec3 aColor;
layout(location = 2) in vec2 aTexCoord;
out vec3 vertexColor;
out vec2 texCoord;
void main()
{
gl_Position = vec4(aPos, 1.0);
vertexColor = aColor;
texCoord = aTexCoord;
}
这是我的片段着色器:
#version 330 core
in vec3 vertexColor;
in vec2 texCoord;
out vec4 FragColor;
uniform sampler2D aTexture;
void main()
{
FragColor = texture(aTexture, texCoord);
};
解决方案
glTexImage2D
在 using 中使用之前尝试翻转像素缓冲区data.flip()
。
此外,在加载纹理时,使用 3 个通道加载它,因为您在glTexImage2D
. 通过更改stbi_load(..., 0)
为 来做到这一点stbi_load(..., 3)
。
推荐阅读
- android - 来自 Firebase 的微调器值,在新数据上添加微调器项
- java - 打印数组元素的所有可能排列
- python - 确定报纸文章中的列数
- vue.js - Vuetify - 如何在轮播中循环多个自定义组件
- typescript - 为什么泛型映射类型的结果不等同于联合类型?
- typescript - 在这种情况下如何使用 TypeScript?
- wordpress - 有人在我的 wordpress 网站上访问了不存在的 /index.html url。可能是什么原因?我能做些什么来防止它?
- php - 如何替换 PHP 文档中的文本?
- pyspark - 如何在 pyspark 数据框范围内构建段链
- java - Hibernate:仅将 ManyToOne 映射到具有特定列值的外键实体