Sampling from a texture in OpenGL is black

与世无争的帅哥 提交于 2021-02-18 18:07:23

问题


I'm trying out my hand at graphics, following a tutorial at http://en.wikibooks.org/wiki/OpenGL_Programming/Modern_OpenGL_Tutorial_06

Problem: When I try to texture my cube, my sample is black.

Screenshot: http://puu.sh/2JP1H.jpg (note: I set blue = uv.x to test my UVs)

I looked at the threads OpenGL textures appear just black, and Texture is all black, but it seemed they had different problems.

First I load my texture using SOIL image loading library:

int w, h;
unsigned char* img = SOIL_load_image("resources/images/4x4window.jpg",&w,&h,0,0);
ErrorIf(!img, "%s", SOIL_last_result());
glGenTextures(1, &texture_id);
glBindTexture(GL_TEXTURE, texture_id);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexImage2D(GL_TEXTURE_2D,0,GL_RGB,w,h,0,GL_RGB,GL_UNSIGNED_BYTE,img);

My render function where I pass my texture to the shader program:

void onDisplay()
{
  glClearColor(1.0, 1.0, 1.0, 1.0);
  glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

  glUseProgram(program);

  glActiveTexture(GL_TEXTURE0);
  glBindTexture(GL_TEXTURE_2D, texture_id);
  glUniform1i(uniform_myTexture, /*GL_TEXTURE*/0);

  glEnableVertexAttribArray(attribute_coord3d); // open shader var
  glBindBuffer(GL_ARRAY_BUFFER, vbo_cube_verts); // put stuff in buffer
  glVertexAttribPointer(attribute_coord3d, 3, GL_FLOAT, GL_FALSE, 0, 0); //send

  glEnableVertexAttribArray(attribute_texcoord);
  glBindBuffer(GL_ARRAY_BUFFER, vbo_cube_texcoords);
  glVertexAttribPointer(attribute_texcoord, 2, GL_FLOAT, GL_FALSE, 0, 0);

  glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ibo_cube_elements);
  int size; 
  glGetBufferParameteriv(GL_ELEMENT_ARRAY_BUFFER, GL_BUFFER_SIZE, &size);
  glDrawElements(GL_TRIANGLES, size / sizeof(GLushort), GL_UNSIGNED_SHORT, 0);

  glDisableVertexAttribArray(attribute_coord3d);
  glDisableVertexAttribArray(attribute_texcoord);

  glutSwapBuffers();
}

Vertex Shader:

attribute vec3 coord3d;
attribute vec2 texcoord;
varying vec2 f_texcoord;
uniform mat4 mvp;

void main(void)
{
  gl_Position = mvp * vec4(coord3d, 1.0);
  f_texcoord = texcoord;
}

Fragment Shader:

varying vec2 f_texcoord;
uniform sampler2D mytexture;

void main(void)
{
  vec4 result = texture2D(mytexture, f_texcoord);

  result.z = f_texcoord.x;
  result.w = 1;

  gl_FragColor = result;
}

回答1:


The line where the the texture is bound is:

glBindTexture(GL_TEXTURE, texture_id);

that should be:

glBindTexture(GL_TEXTURE_2D, texture_id);


来源:https://stackoverflow.com/questions/16290938/sampling-from-a-texture-in-opengl-is-black

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!