【发布时间】:2017-10-19 13:13:31
【问题描述】:
所以基本上我正在尝试在代码中创建自己的纹理。具体来说,我正在编写一个光线追踪器,并希望将结果显示为渲染到屏幕上四边形的纹理。
但是如何创建自己的纹理然后将其应用到屏幕四边形呢?我已经在这几天没有任何特别的结果。我现在得到的是屏幕上的四边形,但纹理是整个四边形的一种颜色。但在我的示例中,我希望它是 1/3 白色和 2/3 黑色,这就是我想象的方式。
我希望 OpenGL 尽可能保持准系统。我不打算扩展它,所以只要它有效,任何包含“丑陋黑客”的答案都是完全可以的。我正在使用 Glew、GLFW 和 GLM。
这就是我目前的做法:
GLFWwindow* window;
//Create a texture that should be 1 third black and 2 thirds white?
unsigned char texdata[SCREEN_HEIGHT * SCREEN_WIDTH * 3];
for(int i=0; i<SCREEN_HEIGHT * SCREEN_WIDTH * 3; i++)
{
if(i < SCREEN_HEIGHT * SCREEN_WIDTH)
texdata[i] = 255;
else
texdata[i] = 0;
}
//cam.createTexture(texdata);
initOpenGL(window);
GLuint t = 0;
glEnable(GL_TEXTURE_2D); // Required for glBuildMipmap() to work (!)
glGenTextures( 1, &t );
glBindTexture(GL_TEXTURE_2D, t);
// Set parameters to determine how the texture is resized
glTexParameteri ( GL_TEXTURE_2D , GL_TEXTURE_MIN_FILTER , GL_LINEAR_MIPMAP_LINEAR );
glTexParameteri ( GL_TEXTURE_2D , GL_TEXTURE_MAG_FILTER , GL_LINEAR );
// Set parameters to determine how the texture wraps at edges
glTexParameteri ( GL_TEXTURE_2D , GL_TEXTURE_WRAP_S , GL_REPEAT );
glTexParameteri ( GL_TEXTURE_2D , GL_TEXTURE_WRAP_T , GL_REPEAT );
// Read the texture data from file and upload it to the GPU
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, SCREEN_WIDTH, SCREEN_HEIGHT, 0,
GL_RGB, GL_UNSIGNED_BYTE, texdata);
glGenerateMipmap(GL_TEXTURE_2D);
GLuint programID = LoadShaders("vertex.glsl", "fragment.glsl");
glUseProgram(programID);
// Create and compile our GLSL program from the shaders
Objects screenquad;
screenquad.createBox(1.0, 1.0, 0.0);
do{
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
screenquad.render();
// Swap buffers
glfwSwapBuffers(window);
glfwPollEvents();
} // Check if the ESC key was pressed or the window was closed
while( glfwGetKey(window, GLFW_KEY_ESCAPE ) != GLFW_PRESS &&
glfwWindowShouldClose(window) == 0 );
GLSL 着色器代码:
#version 450
in vec2 Texcoord;
out vec4 outColor;
uniform sampler2D tex;
void main(){
outColor = texture(tex, Texcoord);
}
还有顶点着色器:
#version 450
layout(location = 0) in vec3 vertexPosition_modelspace;
layout(location = 1) in vec3 Normal;
layout(location = 2) in vec2 texcoord;
out vec2 Texcoord;
void main(){
Texcoord = texcoord;
gl_Position.xyz = vertexPosition_modelspace;
gl_Position.w = 1.0;
}
编辑: 创建 screenquad 的内部结构: https://raw.githubusercontent.com/ddavidtran/Fishualization/master/OpenGL/Objects.cpp
【问题讨论】:
-
你确定你的纹理坐标是正确的吗?所有纹理坐标均为 [0,0] 可能会导致完全白色的纹理。
-
screenquadinternals 的来源会有所帮助。另外,您没有将纹理绑定到着色器程序,这可能是错误的原因。 -
我不是 100% 确定,但是我用来创建屏幕四边形的代码我以前在项目中使用过,它会生成纹理坐标,除了你会。我曾尝试调查纹理坐标是否错误,但我对 OpenGL 的了解不足以得出任何结论....
-
我编辑并包含了指向我创建 screenquad 的 cpp 的链接。这是我之前项目中的一个文件,在那里运行良好。