GLSL实现图片加载及纹理翻转策略
2020-08-04 本文已影响0人
w執念
想要使用OpenGL ES完成图片的加载,大概的流程可以分为以下几点:
1.创建图层
2.创建上下文
3.清空缓存区
4.设置RenderBuffer
5.设置FrameBuffer
6.开始绘制
准备工作
因为是使用自定义着色器,所以我们需要新建两个空文件,分别命名为shaderv.vsh和shaderf.fsh,依次来区分顶点和片元着色器(注意:在这两个文件中添加注释有可能会诱发一些错误)。
//shaderv.vsh
attribute vec4 position; //所显示图片的顶点
attribute vec2 textCoordinate; //纹理坐标
varying lowp vec2 varyTextCoord; //也是纹理坐标,作用是把纹理坐标从顶点传到片元
void main(){
varyTextCoord = textCoordinate; //顶点到片元了
gl_Position = position; //顶点原样输出 gl_Position:内建变量,最终的结果
}
//shaderf.fsh
precision highp float; //定义float类型的精度
varying lowp vec2 varyTextCoord; //纹理坐标
uniform sampler2D colorMap; //传进来的纹理
void main(){
gl_FragColor = texture2D(colorMap, varyTextCoord);//纹理图片,纹理坐标
}
创建图层
这里有一点需要注意,就是我们需要重写layerClass,将其返回的图层从CALayer替换成CAEAGLLayer。
-(void)setupLayer
{
//1.创建特殊图层
self.myEagLayer = (CAEAGLLayer *)self.layer;
//2.设置scale
[self setContentScaleFactor:[[UIScreen mainScreen]scale]];
//3.设置描述属性,这里设置不维持渲染内容以及颜色格式为RGBA8
self.myEagLayer.drawableProperties = [NSDictionary dictionaryWithObjectsAndKeys:@false,kEAGLDrawablePropertyRetainedBacking, kEAGLColorFormatRGBA8,kEAGLDrawablePropertyColorFormat,nil];
}
+(Class)layerClass{
return [CAEAGLLayer class];
}
创建上下文
-(void)setupContext
{
//1.指定OpenGL ES 渲染API版本,我们使用2.0
EAGLRenderingAPI api = kEAGLRenderingAPIOpenGLES2;
//2.创建图形上下文
EAGLContext *context = [[EAGLContext alloc]initWithAPI:api];
//3.判断是否创建成功
if (!context) {
NSLog(@"Create context failed!");
return;
}
//4.设置图形上下文
if (![EAGLContext setCurrentContext:context]) {
NSLog(@"setCurrentContext failed!");
return;
}
//5.将局部context,变成全局的
self.myContext = context;
}
清空缓存区
-(void)deleteRenderAndFrameBuffer
{
glDeleteBuffers(1, &_myColorRenderBuffer);
self.myColorRenderBuffer = 0;
glDeleteBuffers(1, &_myColorFrameBuffer);
self.myColorFrameBuffer = 0;
}
设置RenderBuffer
-(void)setupRenderBuffer
{
//定义一个缓存区ID
GLuint buffer;
//申请一个缓存区标志
glGenRenderbuffers(1, &buffer);
self.myColorRenderBuffer = buffer;
//将标识符绑定到GL_RENDERBUFFER
glBindRenderbuffer(GL_RENDERBUFFER, self.myColorRenderBuffer);
//将可绘制对象drawable object's CAEAGLLayer的存储绑定到OpenGL ES renderBuffer对象
//和myEagLayer绑定
[self.myContext renderbufferStorage:GL_RENDERBUFFER fromDrawable:self.myEagLayer];
}
设置FrameBuffer
设置两个缓冲区的流程基本相比,只有最后设置完后,需要将两个缓冲区绑定并捆绑到附着点上。
-(void)setupFrameBuffer
{
//1.定义一个缓存区ID
GLuint buffer;
//2.申请一个缓存区标志
glGenRenderbuffers(1, &buffer);
//3.
self.myColorFrameBuffer = buffer;
//4.
glBindFramebuffer(GL_FRAMEBUFFER, self.myColorFrameBuffer);
/*生成帧缓存区之后,则需要将renderbuffer跟framebuffer进行绑定,
调用glFramebufferRenderbuffer函数进行绑定到对应的附着点上,后面的绘制才能起作用
*/
//GL_COLOR_ATTACHMENT0附着点
//5.将渲染缓存区myColorRenderBuffer 通过glFramebufferRenderbuffer函数绑定到 GL_COLOR_ATTACHMENT0上。
glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_RENDERBUFFER, self.myColorRenderBuffer);
}
开始绘制
-(void)renderLayer
{
glClearColor(0.3f, 0.45f, 0.5f, 1.0f);
glClear(GL_COLOR_BUFFER_BIT);
//1.设置视口大小
CGFloat scale = [[UIScreen mainScreen]scale];
glViewport(self.frame.origin.x * scale, self.frame.origin.y * scale, self.frame.size.width * scale, self.frame.size.height * scale);
//2.读取顶点着色程序、片元着色程序
NSString *vertFile = [[NSBundle mainBundle]pathForResource:@"shaderv" ofType:@"vsh"];
NSString *fragFile = [[NSBundle mainBundle]pathForResource:@"shaderf" ofType:@"fsh"];
NSLog(@"vertFile:%@",vertFile);
NSLog(@"fragFile:%@",fragFile);
//3.加载shader
self.myPrograme = [self loadShaders:vertFile Withfrag:fragFile];
//4.链接
glLinkProgram(self.myPrograme);
GLint linkStatus;
//获取链接状态
glGetProgramiv(self.myPrograme, GL_LINK_STATUS, &linkStatus);
if (linkStatus == GL_FALSE) {
GLchar message[512];
glGetProgramInfoLog(self.myPrograme, sizeof(message), 0, &message[0]);
NSString *messageString = [NSString stringWithUTF8String:message];
NSLog(@"Program Link Error:%@",messageString);
return;
}
NSLog(@"Program Link Success!");
glUseProgram(self.myPrograme);
//5.设置顶点、纹理坐标
GLfloat attrArr[] =
{
0.5f, -0.5f, -1.0f, 1.0f, 0.0f,
-0.5f, 0.5f, -1.0f, 0.0f, 1.0f,
-0.5f, -0.5f, -1.0f, 0.0f, 0.0f,
0.5f, 0.5f, -1.0f, 1.0f, 1.0f,
-0.5f, 0.5f, -1.0f, 0.0f, 1.0f,
0.5f, -0.5f, -1.0f, 1.0f, 0.0f,
};
//6.-----处理顶点数据--------
GLuint attrBuffer;
glGenBuffers(1, &attrBuffer);
glBindBuffer(GL_ARRAY_BUFFER, attrBuffer);
glBufferData(GL_ARRAY_BUFFER, sizeof(attrArr), attrArr, GL_DYNAMIC_DRAW);
//7.将顶点数据通过myPrograme中的传递到顶点着色程序的position
GLuint position = glGetAttribLocation(self.myPrograme, "position");
//设置合适的格式从buffer里面读取数据
glEnableVertexAttribArray(position);
//设置读取方式
glVertexAttribPointer(position, 3, GL_FLOAT, GL_FALSE, sizeof(GLfloat) * 5, NULL);
//8.----处理纹理数据-------
GLuint textCoor = glGetAttribLocation(self.myPrograme, "textCoordinate");
glEnableVertexAttribArray(textCoor);
glVertexAttribPointer(textCoor, 2, GL_FLOAT, GL_FALSE, sizeof(GLfloat)*5, (float *)NULL + 3);
//9.加载纹理
[self setupTexture:@"touxiang"];
//10. 设置纹理采样器 sampler2D
glUniform1i(glGetUniformLocation(self.myPrograme, "colorMap"), 0);
//11.绘图
glDrawArrays(GL_TRIANGLES, 0, 6);
//12.从渲染缓存区显示到屏幕上
[self.myContext presentRenderbuffer:GL_RENDERBUFFER];
}
//从图片中加载纹理
- (GLuint)setupTexture:(NSString *)fileName {
//1、将 UIImage 转换为 CGImageRef
CGImageRef spriteImage = [UIImage imageNamed:fileName].CGImage;
if (!spriteImage) {
NSLog(@"Failed to load image %@", fileName);
exit(1);
}
//2、读取图片的大小,宽和高
size_t width = CGImageGetWidth(spriteImage);
size_t height = CGImageGetHeight(spriteImage);
//3.获取图片字节数 宽*高*4(RGBA)
GLubyte * spriteData = (GLubyte *) calloc(width * height * 4, sizeof(GLubyte));
//4.创建上下文
CGContextRef spriteContext = CGBitmapContextCreate(spriteData, width, height, 8, width*4,CGImageGetColorSpace(spriteImage), kCGImageAlphaPremultipliedLast);
//5、在CGContextRef上--> 将图片绘制出来
CGRect rect = CGRectMake(0, 0, width, height);
//6.使用默认方式绘制
CGContextDrawImage(spriteContext, rect, spriteImage);
//7、画图完毕就释放上下文
CGContextRelease(spriteContext);
//8、绑定纹理到默认的纹理ID(
glBindTexture(GL_TEXTURE_2D, 0);
//9.设置纹理属性
glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR );
glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR );
glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
float fw = width, fh = height;
//10.载入纹理2D数据
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, fw, fh, 0, GL_RGBA, GL_UNSIGNED_BYTE, spriteData);
//11.释放spriteData
free(spriteData);
return 0;
}
纹理翻转
这样我们就实现了一个图片的加载,但是运行后发现加载的图片是倒置的,这是因为纹理坐标的原点(0,0)是在左下角,而屏幕的坐标原点(0,0)是在左上角,此时我们想要将图片显示正确的话,有以下几张方法:
- GLKTextureLoader载入纹理时
载入时options设置 GLKTextureLoaderOriginBottomLeft 。
NSDictionary *options = @{GLKTextureLoaderOriginBottomLeft : @(YES)};
GLKTextureInfo *textureInfo = [GLKTextureLoader textureWithContentsOfFile:filePath options:options error:nil];
2.解压图片时,将图片翻转
CGImageRef spriteImage = [UIImage imageNamed:fileName].CGImage;
size_t width = CGImageGetWidth(spriteImage);
size_t height = CGImageGetHeight(spriteImage);
GLubyte *spriteData = (GLubyte *) calloc(width * height * 4, sizeof(GLubyte));
CGContextRef spriteContext = CGBitmapContextCreate(spriteData, width, height, 8, width*4, CGImageGetColorSpace(spriteImage), kCGImageAlphaPremultipliedLast);
CGRect rect = CGRectMake(0, 0, width, height);
CGContextTranslateCTM(spriteContext, 0, rect.size.height);
CGContextScaleCTM(spriteContext, 1.0, -1.0);
CGContextDrawImage(spriteContext, rect, spriteImage);
CGContextRelease(spriteContext);
glBindTexture(GL_TEXTURE_2D, 0);
- 设置旋转矩阵,shader中旋转顶点,不翻转纹理
GLuint rotate = glGetUniformLocation(self.program, "rotateMatrix");
float radians = M_PI;
float sinR = sin(radians);
float cosR = cos(radians);
GLfloat zRotation[16] = {
cosR, -sinR, 0, 0,
sinR, cosR, 0, 0,
0, 0, 1.0, 0,
0.0, 0, 0, 1.0
};
glUniformMatrix4fv(rotate, 1, GL_FALSE, (GLfloat *)&zRotation[0]);
4.设置翻转的纹理坐标映射关系
GLfloat datas[] =
{
0.5f, -0.5f, 0.0f, 1.0f, 1.0f, //右下
-0.5f, 0.5f, 0.0f, 0.0f, 0.0f, // 左上
-0.5f, -0.5f, 0.0f, 0.0f, 1.0f, // 左下
0.5f, 0.5f, 0.0f, 1.0f, 0.0f, // 右上
-0.5f, 0.5f, 0.0f, 0.0f, 0.0f, // 左上
0.5f, -0.5f, 0.0f, 1.0f, 1.0f, // 右下
};
- 修改顶点着色器的纹理坐标
attribute vec4 position;
attribute vec2 textCoordinate;
varying lowp vec2 varyTextCoord;
void main()
{
varyTextCoord = vec2(textCoordinate.x, 1.0-textCoordinate.y);
gl_Position = position;
}
- 修改顶点着色器的纹理坐标
varying lowp vec2 varyTextCoord;
uniform sampler2D colorMap;
void main()
{
lowp coord = vec2(varyTextCoord.x, 1.0-varyTextCoord.y);
gl_FragColor = texture2D(colorMap, coord);
}