程序员OpenGL ES

GLSL实现对Shader编译链接

2019-06-15  本文已影响66人  聪莞

GLSL中对Shader的编译、链接、使用流程:

创建编写shader程序

顶点着色器程序:

//文件名:shaderv.vsh 后面会使用
attribute vec4 position;
attribute vec2 textureCoor;
varying lowp vec2 varyTextCoor;


void main() {
    varyTextCoor = textureCoor;
    gl_Position = position;
}

片元着色器程序:

// 文件名 : shaderf.fsh 后面会使用
uniform sampler2D colorMap;
varying lowp vec2 varyTextCoor;

void main() {
    lowp vec4 temp = texture2D(colorMap,varyTextCoor);
    gl_FragColor = temp;
}

核心代码

传入顶点着色器的路径和片元着色器的路径来生成最终可执行的program

- (GLuint)loadShaders:(NSString *)verFile :(NSString *)fragFile {
    GLuint verShader,fragShader;
    GLuint programe = glCreateProgram();
    
    //开始编译shader
    [self compileShader:&verShader path:verFile type:GL_VERTEX_SHADER];
    [self compileShader:&fragShader path:fragFile type:GL_FRAGMENT_SHADER];
    
    //将编译完的shader附着到program上
    glAttachShader(programe, verShader);
    glAttachShader(programe, fragShader);
    
    //附着完成后删除shader
    glDeleteShader(verShader);
    glDeleteShader(fragShader);
    
    //返回可供使用的program
    return programe;
}

- (void)compileShader:(GLuint *)shader path:(NSString *)path type:(GLenum)type {
    //读取shader文件信息
    NSString *str = [[NSString alloc]initWithContentsOfFile:path encoding:NSUTF8StringEncoding error:nil];
    const GLchar *source = (GLchar *)[str UTF8String];

    //创建一个shader
    *shader = glCreateShader(type);


    //将着色器源码附加到着色器对象上。
    //参数1:shader,要编译的着色器对象 *shader
    //参数2:numOfStrings,传递的源码字符串数量 1个
    //参数3:strings,着色器程序的源码(真正的着色器程序源码)
    //参数4:lenOfStrings,长度,具有每个字符串长度的数组,或NULL,这意味着字符串是NULL终止的
    glShaderSource(*shader, 1, &source, NULL);
    
    //glCompileShader编译shader
    glCompileShader(*shader);
}

使用GLSL实现一张图片的加载

实现流程:

初始化的一些属性数据:

@property (strong,nonatomic) CAEAGLLayer *myEagLayer;
@property (strong,nonatomic) EAGLContext *myContext;
@property (assign,nonatomic) GLuint myColorRenderBuffer;
@property (assign,nonatomic) GLuint myColorFrameBuffer;
@property (assign,nonatomic) GLuint myPrograme;
  1. 初始化 CAEAGLLayer
    self.myEagLayer = (CAEAGLLayer *)self.layer;
    [self setContentScaleFactor:[[UIScreen mainScreen]scale]];
    self.myEagLayer.drawableProperties = [NSDictionary dictionaryWithObjectsAndKeys:@false,kEAGLDrawablePropertyRetainedBacking, kEAGLColorFormatRGBA8,kEAGLDrawablePropertyColorFormat,nil];
  1. 设置EAGLContext
    EAGLRenderingAPI api = kEAGLRenderingAPIOpenGLES2;
    EAGLContext *context = [[EAGLContext alloc]initWithAPI:api];

    if (!context) {
        NSLog(@"Create context failed!");
        return;
    }
    if (![EAGLContext setCurrentContext:context]) {
        NSLog(@"setCurrentContext failed!");
        return;
    }
    self.myContext = context;
  1. 创建之前清空RenderBuffer和FrameBuffer,也可以不写,习惯问题
    glDeleteBuffers(1, &_myColorRenderBuffer);
    self.myColorRenderBuffer = 0;
   
    glDeleteBuffers(1, &_myColorFrameBuffer);
    self.myColorFrameBuffer = 0;
  1. 创建RenderBuffer
    glGenRenderbuffers(1, &_myColorRenderBuffer);
    
    glBindRenderbuffer(GL_RENDERBUFFER, self.myColorRenderBuffer);
    
    //将可绘制对象drawable object's  CAEAGLLayer的存储绑定到OpenGL ES renderBuffer对象
    [self.myContext renderbufferStorage:GL_RENDERBUFFER fromDrawable:self.myEagLayer];
  1. 创建FrameBuffer
    glGenBuffers(1, &_myColorFrameBuffer);
    glBindFramebuffer(GL_FRAMEBUFFER, self.myColorFrameBuffer);
    
    /*生成帧缓存区之后,则需要将renderbuffer跟framebuffer进行绑定,
     调用glFramebufferRenderbuffer函数进行绑定到对应的附着点上,后面的绘制才能起作用
     */
    
    //将渲染缓存区myColorRenderBuffer 通过glFramebufferRenderbuffer函数绑定到 GL_COLOR_ATTACHMENT0上。
    glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_RENDERBUFFER, self.myColorRenderBuffer);
  1. 开始渲染
    glClearColor(0.3f, 0.45f, 0.5f, 1.0f);
    glClear(GL_COLOR_BUFFER_BIT);
    
    //设置视口
    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);
    
    NSString *vertFile = [NSBundle.mainBundle pathForResource:@"shaderv" ofType:@"vsh"];
    NSString *fragFile = [NSBundle.mainBundle pathForResource:@"shaderf" ofType:@"fsh"];
    
    self.myPrograme = [self loadShaders:vertFile :fragFile];
    
    //链接
    glLinkProgram(self.myPrograme);
    
    GLint linkStatus;
    glGetProgramiv(self.myPrograme, GL_LINK_STATUS, &linkStatus);
    if (linkStatus == GL_FALSE) {
        GLchar message[1024] ;
        glGetProgramInfoLog(self.myPrograme, sizeof(message), 0, message);
        NSString * str = [NSString stringWithUTF8String:message];
        NSLog(@"programe link error = %@",str);
        return;
    }
    NSLog(@"programe link success !");
    
    //link成功就可以开始使用了
    glUseProgram(self.myPrograme);

后面的流程跟上一篇的OpenGL ES - GLKit初探 配置顶点数据的流程
类似,只是GLKit对着色器程序进行了封装并有了固定的键来表示顶点和纹理(GLKVertexAttribPosition和GLKVertexAttribTexCoord0),而在GLSL中需要我们自己来获取这条通道ID。GLKit中可以通过GLBaseEffect来加载纹理,而在GLSL中也是需要自己去加载纹理。

通过glGetAttribLocation来获取attribute修饰的变量通道
     //传递顶点
    GLuint position = glGetAttribLocation(self.myPrograme, "position");
    glEnableVertexAttribArray(position);
    glVertexAttribPointer(position, 3, GL_FLOAT, GL_FALSE, sizeof(GLfloat) * 5, NULL);

    //传递纹理
    GLuint textCoor = glGetAttribLocation(self.myPrograme, "textureCoor");
    glEnableVertexAttribArray(textCoor);
    glVertexAttribPointer(textCoor, 2, GL_FLOAT, GL_FALSE, sizeof(GLfloat)*5, (float *)NULL + 3);
加载纹理
    [self setupTexture:@"memory.jpg"];
    //设置纹理采样
    glUniform1f(glGetUniformLocation(self.myPrograme, "colorMap"), 0);
    glDrawArrays(GL_TRIANGLES, 0, 6);
    [self.myContext presentRenderbuffer:GL_RENDERBUFFER];
//读取纹理
- (void)setupTexture:(NSString *)name {
    CGImageRef imgRef = [UIImage imageNamed:name].CGImage;
    if (imgRef == nil) {
        return;
    }
    size_t width = CGImageGetWidth(imgRef);
    size_t height = CGImageGetHeight(imgRef);
    
    //获取图片总字节数
    GLubyte *imgData = calloc(width * height * 4, sizeof(GLubyte));
    
    CGContextRef imgContext = CGBitmapContextCreate(imgData, width, height, 8, width * 4, CGImageGetColorSpace(imgRef), kCGImageAlphaPremultipliedLast);
    
    CGRect rect = CGRectMake(0, 0, width, height);
    CGContextDrawImage(imgContext, rect, imgRef);
    
    CGContextRelease(imgContext);
    
    //开始绑定纹理
    glBindTexture(GL_TEXTURE_2D, 0);
    
    //设置属性
    glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
    glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
    glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
    glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
    
    float fw = width,fh = height;
    glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, fw, fh, 0, GL_RGBA, GL_UNSIGNED_BYTE, imgData);
    
    free(imgData);
}

Demo链接:https://download.csdn.net/download/zc971188623/11242297

上一篇下一篇

猜你喜欢

热点阅读