您的位置:首页 > 运维架构

OPENGL视频学习(八)

2016-11-06 15:52 225 查看
OPENGL实现纹理.

首先准备纹理图片,随便到网上自己需要的图片下载。

实现加载图片的库,www.oxox.work/web/opengl/opengl07, stb_image.h 密码 3b7i stb_image.cpp 密码 bpwk bricks.jpg 密码 4t2k 也可以自己写加载图片的函数

添加纹理类Texture

Texture.h

#include <GL/glew.h>

class Texture

{

public:

Texture(const std::string& fileName);

void Bind();

~Texture();

private:

GLuint m_texture;

};

源文件

#include "Texture.h"

#include “stb_image.h“

Texture::Texture(const std::string& fileName)

{

int width,height,numComponent;

unsigned char* data=stb_load(fileName.c_str,&width,&height,&numComponent,4);

if(data==NULL)

{

std::cerr<<"无法加载纹理"<<fileName<<std::endl;

}

glGenTextures(1,&m_texture);

glBindTexture(GL_TEXTURE_2D,m_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_LINERA);

glTexImage2D(GL_TEXTURE_2D,0,GL_RGBA,width,height,0,GL_RGBA,GL_UNSIGNED_BYTE,data);

stdbi_image_free(data);

}

析构函数

Texture::~Texture()

{

glDeleteTexture(GL_TEXTURE_2D,&m_texture);

}

//添加绑定函数

void Texture::Bind()

{

glBindTexture(GL_TEXTURE_2D,m_texture);

}

从而可以在main函数种调用他

main.cpp

在shader的后面

Texture texture("./res/bricks.jpg");

在while循环中,绑定它,texture.bind();

发现纹理没有添加上,因为前面我们在basic.shader中设置颜色为红色

uniform sampler2d diffuse;

gl_FragColor=texture2D(diffuse,vec2(0.2,0.2));

如何出现整个纹理的颜色,传递一张纹理,不能是固定的点,glm::vec2 texCoord;

在vertex种添加vertex(const glm::vec3& cos,const glm::vec2& texCoord)

{

this->pos=pos;

this->texCoord=texCoord;

}

添加纹理缓冲
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息