紫色取代了纹理颜色

时间:2019-01-13 23:13:15

标签: opengl nim

我尝试在四边形上显示纹理,但颜色已替换为一些紫色。     enter image description here

该代码的灵感来自“ learnopengl”网站,但我没有发现失败的原因。 这里是着色器。

vertSrc:cstring = """
    #version 330 core

    layout (location = 0) in vec3 aPos;
    layout (location = 1) in vec2 aTexCoord;

    out vec2 texCoord;
    uniform mat4 projection;

    void main()
    {
        gl_Position = projection * vec4(aPos, 1.0f);
        texCoord = aTexCoord;
    }
    """
fragSrc:cstring = """
    #version 330 core

    out vec4 FragColor;
    in vec2 texCoord;

    uniform sampler2D matTexture;

    void main()
    {
        FragColor = texture(matTexture, texCoord);
    }

    """

纹理的opengl代码。

glGenTextures(1, addr textureID)
glBindTexture(GL_TEXTURE_2D, textureID)
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)
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, texWidth, texHeight, 0, GL_RGB, GL_UNSIGNED_BYTE, addr imageData[0])
glGenerateMipmap(GL_TEXTURE_2D)

通过stb_image库加载图像。

var 
textureID:OGLuint
texWidth:OGLint
texHeight:OGLint
channelCount:OGLint
imageData = stbi_load("Test/2d-rendering-test./stack.png", addr texWidth, addr texHeight, addr channelCount, 0)

以及主循环中的opengl代码。

glBindTexture(GL_TEXTURE_2D, textureID)

如果您对此感到好奇,请显示一个完整的nim文件来显示问题。 https://bitbucket.org/Neotry/2d-rendering-test./src/master/WIPtest.nim

1 个答案:

答案 0 :(得分:1)

Portable Network Graphics (PNG)文件可能包含32位RGBA颜色。

通过将4显式传递给最后一个参数,强制stbi_load生成具有4个颜色通道的图像:

imageData = stbi_load("Test/2d-rendering-test./stack.png",
                      addr texWidth, addr texHeight, addr channelCount, 4)

请参见stb_image.h

Basic usage (see HDR discussion below for HDR usage):
      int x,y,n;
      unsigned char *data = stbi_load(filename, &x, &y, &n, 0);
      // ... process data if not NULL ...
      // ... x = width, y = height, n = # 8-bit components per pixel ...
     

// ... replace '0' with '1'..'4' to force that many components per pixel

      // ... but 'n' will always be the number that it would have been if you said 0
      stbi_image_free(data)

最后,glTexImage2D的格式参数必须为GL_RGBAGL_BGRA。对于内部格式,可以保留GL_RGB

glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, texWidth, texHeight, 0, GL_RGBA,
             GL_UNSIGNED_BYTE, addr imageData[0])  
相关问题