//MARK: 着色器程序
/// 着色器程序启动
/// @param vertex <#vertex description#>
/// @param fragment <#fragment description#>
-(GLuint)startShaderProgram:(NSString *)vertex fFile:(NSString *)fragment{
//定义2个零时着色器对象
GLuint verSharder, fragSharder;
//着色器编译
[self compileShader:&verSharder type:GL_VERTEX_SHADER path:vertex];
[self compileShader:&fragSharder type:GL_FRAGMENT_SHADER path:fragment];
//程序编译
GLuint program;
program = [self compileProgram:verSharder frag:fragSharder];
//程序链接
[self linkProgram:program];
return program;
}
/// 顶点着色器创建、编译
/// @param shader <#shader description#>
/// @param type <#type description#>
/// @param path <#path description#>
-(void)compileShader:(GLuint *)shader type:(GLenum)type path:(NSString *)path{
//1. 顶点、片元着色器ID创建
*shader = glCreateShader(type);
//2. 读取着色器文件
NSString *source = [NSString stringWithContentsOfFile:path encoding:NSUTF8StringEncoding error:nil];
//转为c字符串
const GLchar* cSource = [source UTF8String];
//3.将着色器源码附加到着色器对象上。
//参数1:shader,要编译的着色器对象 *shader
//参数2:numOfStrings,传递的源码字符串数量 1个
//参数3:strings,着色器程序的源码(真正的着色器程序源码)
//参数4:lenOfStrings,长度,具有每个字符串长度的数组,或NULL,这意味着字符串是NULL终止的
glShaderSource(*shader, 1, &cSource, NULL);
//4.着色器编译
glCompileShader(*shader);
}
/// 程序对象创建
/// @param vertexShader <#vertexShader description#>
/// @param fragShader <#fragShader description#>
-(GLuint)compileProgram:(GLuint)vertexShader frag:(GLuint)fragShader {
//5. 程序ID创建
GLint program = glCreateProgram();
//6. 着色器附着到程序上,创建最终的程序
glAttachShader(program, vertexShader);
glAttachShader(program, fragShader);
//7. 不会立即删除着色器,而是将着色器进行标记,等待着色器不在连接任何程序对象时,他的内存将会被释放。
glDeleteShader(vertexShader);
glDeleteShader(fragShader);
return program;
}
/// 程序链接
-(void)linkProgram:(GLuint)program {
//8. 程序链接
glLinkProgram(program);
GLint linkStatus;
//获取编译状态
glGetProgramiv(program, GL_LINK_STATUS, &linkStatus);
if (linkStatus == GL_FALSE) {
GLchar info[512];
glGetProgramInfoLog(program, sizeof(info), 0, &info[0]);
NSString *message = [NSString stringWithUTF8String: info];
NSLog(@"Program Link Error:%@",message);
return;
}
NSLog(@"Program Link Success!");
//9.使用program
glUseProgram(program);
}
网友评论