一、代码
正常效果
1.顶点着色器
attribute vec4 Position;
attribute vec2 TextureCoords;
varying vec2 TextureCoordsVarying;
void main (void) {
gl_Position = Position;
TextureCoordsVarying = TextureCoords;
}
2.片元着色器
precision highp float;
uniform sampler2D Texture;
varying vec2 TextureCoordsVarying;
void main (void) {
vec4 mask = texture2D(Texture, TextureCoordsVarying);
gl_FragColor = vec4(mask.rgb, 1.0);
}
2、缩放
最简单的实现方法:在顶点着色器中,随着时间的变化,让顶点坐标的x、y乘以对应时间的放大比例
,来实现缩放效果。
我们只修改顶点着色器
:
attribute vec4 Position;
attribute vec2 TextureCoords;
varying vec2 TextureCoordsVarying;
//随着定时器的刷新方法不断增加的时间戳,一直在累加
uniform float Time;
//π
const float PI = 3.1415926;
void main (void) {
//一次缩放效果的时长,0.6秒缩放一次
float duration = 0.6;
//最大缩放幅度,从1放大到1.3倍
float maxAmplitude = 0.3;
//表示传入的事件周期,即time的范围被控制在0.0~0.6,然后根据周期,计算当前这一秒在周期内的位置,来计算,这一秒图片的状态
//mod(a, b),求模运算 等价于 a%b,GLSL中不支持%求模
float time = mod(Time,duration);
//amplitude表示振幅,也就是放大比例,引入PI的目的是为了使用sin函数,将amplitude的范围控制在1.0 ~ 1.3之间,并随着时间变化
//这里可以不用取绝对值,因为角度的范围是【0,π】,不会出现负数的情况
float amplitude = 1.0 + maxAmplitude * abs(sin(time * (PI / duration)));
//将顶点坐标的x和y分别乘以一个放大比例,在纹理坐标不变的情况下,就达到了放大拉伸的效果
//xy放大,zw保持不变
gl_Position = vec4(Position.x * amplitude, Position.y * amplitude, Position.zw);
TextureCoordsVarying = TextureCoords;
}
3、灵魂出窍
原理:两张图片叠加在一起,进行颜色混合
,然后上层图片随着时间戳的变化,进行变放大、变减少透明度。
precision highp float;
uniform sampler2D Texture;
varying vec2 TextureCoordsVarying;
uniform float Time;
void main (void) {
//周期
float duration = 0.7;
//最大透明度0.4
float maxAlpha = 0.4;
//最大放大1.8倍
float maxScale = 1.8;
//算出当前时间 在周期内的 占比。这一秒,应该是周期内第几秒展示的效果
float progress = mod(Time, duration) / duration; // 0~1
//当前秒的透明度,因为progress是【0 ~ 1】,1.0 - progress就是【1 ~ 0】,透明度范围就是【0.4 ~ 0】
float alpha = maxAlpha * (1.0 - progress);
//当前秒的放大比例
float scale = 1.0 + (maxScale - 1.0) * progress;
//算出某一个点,以中心点(0.5,0.5)为参照,经过放大比例后所在的新位置,就可以得到这个点新的纹理坐标
float weakX = 0.5 + (TextureCoordsVarying.x - 0.5) / scale;
float weakY = 0.5 + (TextureCoordsVarying.y - 0.5) / scale;
vec2 weakTextureCoords = vec2(weakX, weakY);
//上层图片的纹素
vec4 weakMask = texture2D(Texture, weakTextureCoords);
//底层图片的纹素
vec4 mask = texture2D(Texture, TextureCoordsVarying);
//混合
gl_FragColor = mask * (1.0 - alpha) + weakMask * alpha;
}
4、抖动
原理:颜色偏移+微弱的放大
。就是先将纹理放大,然后将放大后的纹理坐标的纹素进行颜色偏移
precision highp float;
uniform sampler2D Texture;
varying vec2 TextureCoordsVarying;
uniform float Time;
void main (void) {
//周期
float duration = 0.7;
//最大放大到1.1倍
float maxScale = 1.1;
//颜色偏移步长
float offset = 0.02;
//当前这一秒的进度
float progress = mod(Time, duration) / duration; // 0~1
//当前这一秒的颜色偏移量,范围【0 ~ 0.02】
vec2 offsetCoords = vec2(offset, offset) * progress;
//当前这一秒的放大比例 【1 ~ 1.1】
float scale = 1.0 + (maxScale - 1.0) * progress;
//计算这一秒 每个像素点所在的新纹理坐标
float weakX = 0.5 + (TextureCoordsVarying.x - 0.5) / scale;
float weakY = 0.5 + (TextureCoordsVarying.y - 0.5) / scale;
vec2 ScaleTextureCoords0 = vec2(weakX, weakY);
//也可以这么写
vec2 ScaleTextureCoords = vec2(0.5, 0.5) + (TextureCoordsVarying - vec2(0.5, 0.5)) / scale;
//纹素
vec4 mask = texture2D(Texture, ScaleTextureCoords);
//颜色偏移的纹素
vec4 maskR = texture2D(Texture, ScaleTextureCoords + offsetCoords);
vec4 maskB = texture2D(Texture, ScaleTextureCoords - offsetCoords);
//从3组颜色中分别获取RGBA的值
gl_FragColor = vec4(maskR.r, mask.g, maskB.b, mask.a);
}
5、闪白
原理:两个图层混合,不过上层图片是一个纯白色的遮罩。随着时间的推移变淡。
precision highp float;
uniform sampler2D Texture;
varying vec2 TextureCoordsVarying;
uniform float Time;
const float PI = 3.1415926;
void main (void) {
//一个周期的时长
float duration = 0.6;
//当前时间在周期内的某一秒
float time = mod(Time, duration);
//白色遮罩图层
vec4 whiteMask = vec4(1.0, 1.0, 1.0, 1.0);
//随着时间变化的振幅,【0 ~ 1】
float amplitude = abs(sin(time * (PI / duration)));
//纹理图层
vec4 mask = texture2D(Texture, TextureCoordsVarying);
//颜色混合
gl_FragColor = mask * (1.0 - amplitude) + whiteMask * amplitude;
}
6、毛刺
mod函数计算时间周期:floattime =mod(Time, duration *2.0);
计算振幅,范围是「0, 1]:floatamplitude =max(sin(time * (PI / duration)),0.0);
获取像素点随机偏移值,范围是[-1,1]:floatjitter = rand(TextureCoordsVarying.y) *2.0-1.0;// -1~1
判断是否需要偏移 & 计算纹理的x坐标
需要偏移,撕裂较大,即x的颜色偏移较大
不需要,撕裂较小,即x的颜色偏移值很微小
获取撕裂后的纹理坐标
计算撕裂后的3组纹素,并获取不同组中的RGBA值
precision highp float;
uniform sampler2D Texture;
varying vec2 TextureCoordsVarying;
uniform float Time;
const float PI = 3.1415926;
/*
因为没有内置的随机函数,这里自定义一个随机数方法
fract(x):返回x的小数部分
返回:sin(n)*一个带小数点的极大值
想要随机数算的比较低,乘的数就必须较大,噪声随机
如果想得到【0,1】范围的小数值,可以将sin * 1
*/
float rand(float n) {
return fract(sin(n) * 43758.5453123);
}
void main (void) {
//设定一个阈值,意思是最大抖动的值
float maxJitter = 0.06;
//周期
float duration = 0.3;
//红色偏移值
float colorROffset = 0.01;
//蓝色偏移值
float colorBOffset = -0.025;
//设定当前秒,它的范围【0 ~ 0.6】 duration*2.0是为了设置一个值
float time = mod(Time, duration * 2.0);
//当前振幅 范围【1 ~ 1.3】
float amplitude = max(sin(time * (PI / duration)), 0.0);
//得到一个【-1 ~ 1】的随机值
float jitter = rand(TextureCoordsVarying.y) * 2.0 - 1.0; // -1~1
//判断是否需要撕裂
// abs(jitter) 范围【0,1】
// maxJitter * amplitude 范围【0, 0.06】
//如果偏移值太大,就不是轻微撕裂效果了,会很夸张 类似画面故障了
bool needOffset = abs(jitter) < maxJitter * amplitude;
//拿到撕裂的x值
float textureX = TextureCoordsVarying.x + (needOffset ? jitter : (jitter * amplitude * 0.006));
//撕裂后的纹理坐标
vec2 textureCoords = vec2(textureX, TextureCoordsVarying.y);
//撕裂后的纹素
vec4 mask = texture2D(Texture, textureCoords);
//撕裂后 颜色偏移的纹素
vec4 maskR = texture2D(Texture, textureCoords + vec2(colorROffset * amplitude, 0.0));
vec4 maskB = texture2D(Texture, textureCoords + vec2(colorBOffset * amplitude, 0.0));
//取3个纹素的随机RBGA
gl_FragColor = vec4(maskR.r, mask.g, maskB.b, mask.a);
}
7、幻觉
这里其实结合了上面的知识,有的模拟器跑不起来,真机无压力。
原理:残影+颜色偏移
残影:每隔一个时间段,就会新建一个图层,这个图层以红色为主,然后随着时间的推移透明度降低。多个图层相互有距离地随着时间变化做圆周运动,从而形成残影效果。
颜色偏移:图片在移动的过程中是蓝色在前,红色在后,即在移动的过程中,每间隔一段时间,遗失了一部分红色通道的值在原来的位置,并且这部分红色通道的值,随着时间偏移,会逐渐恢复
precision highp float;
uniform sampler2D Texture;
varying vec2 TextureCoordsVarying;
uniform float Time;
const float PI = 3.1415926;
//周期,因为封装方法要用到,单拎出来
const float duration = 2.0;
/*
转圈产生幻影的单个像素点的颜色值
计算在当前秒当前像素的具体位置,也就是某个时刻图片的具体位置。
*/
vec4 getMask(float time, vec2 textureCoords, float padding) {
//圆心坐标
vec2 translation = vec2(sin(time * (PI * 2.0 / duration)),
cos(time * (PI * 2.0 / duration)));
//新的纹理坐标 = 原始纹理坐标 + 偏移量 * 圆周坐标(新的图层与图层之间是有间距的,所以需要偏移)
vec2 translationTextureCoords = textureCoords + padding * translation;
//根据新的纹理坐标获取新图层的纹素
vec4 mask = texture2D(Texture, translationTextureCoords);
return mask;
}
/*
计算 某个时刻创建的层,在当前时刻的透明度
*/
float maskAlphaProgress(float currentTime, float hideTime, float startTime) {
//mod(周期+持续时间-开始时间,周期)得到一个周期内的time
float time = mod(duration + currentTime - startTime, duration);
//如果小于0.9,返回time,反之,返回0.9
return min(time, hideTime);
}
void main (void) {
//周期内 当前的秒数 范围【0 ~ 2】
float time = mod(Time, duration);
//放大的倍数
float scale = 1.2;
//偏移量
float padding = 0.5 * (1.0 - 1.0 / scale);
//放大后的纹理坐标
vec2 textureCoords = vec2(0.5, 0.5) + (TextureCoordsVarying - vec2(0.5, 0.5)) / scale;
//多出来的图层隐藏的时间
float hideTime = 0.9;
//增加图层的时间间隔
float timeGap = 0.2;
//红色为主的幻影的R G B
//注意:只保留了红色的透明的通道值,因为幻觉效果残留红色
float maxAlphaR = 0.5; // max R
float maxAlphaG = 0.05; // max G
float maxAlphaB = 0.05; // max B
//根据传入时间、纹理坐标、偏移量,获取新的图层的坐标
vec4 mask = getMask(time, textureCoords, padding);
//RGB :for循环中使用
float alphaR = 1.0; // R
float alphaG = 1.0; // G
float alphaB = 1.0; // B
//最终图层颜色:初始化
vec4 resultMask = vec4(0, 0, 0, 0);
//循环:每一层循环都会得到新的图层的颜色,即幻影颜色
//一次循环只是计算一个像素点的纹素,需要在真机运行。模拟器会卡,主要是模拟器上是CPU模拟GPU的
for (float f = 0.0; f < duration; f += timeGap) {
float tmpTime = f;
//获得幻影当前时间的颜色值
vec4 tmpMask = getMask(tmpTime, textureCoords, padding);
//某个时刻创建的层,在当前时刻的红绿蓝的透明度
//临时的透明度 = 根据时间推移RGB的透明度发生变化
//获得临时的红绿蓝透明度
float tmpAlphaR = maxAlphaR - maxAlphaR * maskAlphaProgress(time, hideTime, tmpTime) / hideTime;
float tmpAlphaG = maxAlphaG - maxAlphaG * maskAlphaProgress(time, hideTime, tmpTime) / hideTime;
float tmpAlphaB = maxAlphaB - maxAlphaB * maskAlphaProgress(time, hideTime, tmpTime) / hideTime;
//累计每一层临时RGB * RGB的临时透明度
//结果 += 临时颜色 * 透明度,即刚产生的图层的颜色
resultMask += vec4(tmpMask.r * tmpAlphaR,
tmpMask.g * tmpAlphaG,
tmpMask.b * tmpAlphaB,
1.0);
//透明度递减
alphaR -= tmpAlphaR;
alphaG -= tmpAlphaG;
alphaB -= tmpAlphaB;
}
//最终颜色 += 原始纹理的RGB * 透明度
resultMask += vec4(mask.r * alphaR, mask.g * alphaG, mask.b * alphaB, 1.0);
gl_FragColor = resultMask;
}
三、代码部分
#import "ViewController.h"
#import <GLKit/GLKit.h>
#import "FilterBar.h"
//之前也提到过,c语言结构体,存放顶点数据
typedef struct {
GLKVector3 positionCoord; // (X, Y, Z)
GLKVector2 textureCoord; // (U, V)
} SenceVertex;
@interface ViewController ()<FilterBarDelegate>
// 顶点数组
@property (nonatomic, assign) SenceVertex *vertices;
// 上下文
@property (nonatomic, strong) EAGLContext *context;
// 用于刷新屏幕的专属定时器(相比timer,它可以和屏幕刷新同频)
@property (nonatomic, strong) CADisplayLink *displayLink;
// 开始的时间戳
@property (nonatomic, assign) NSTimeInterval startTimeInterval;
// 着色器程序
@property (nonatomic, assign) GLuint program;
// 顶点缓冲区id
@property (nonatomic, assign) GLuint vertexBuffer;
// 纹理的id
@property (nonatomic, assign) GLuint textureID;
@end
@implementation ViewController
//释放部分
- (void)dealloc {
//上下文释放
if ([EAGLContext currentContext] == self.context) {
[EAGLContext setCurrentContext:nil];
}
//顶点缓存区释放
if (_vertexBuffer) {
glDeleteBuffers(1, &_vertexBuffer);
_vertexBuffer = 0;
}
//顶点数组释放
if (_vertices) {
free(_vertices);
_vertices = nil;
}
}
- (void)viewWillDisappear:(BOOL)animated {
[super viewWillDisappear:animated];
// 移除 displayLink
if (self.displayLink) {
[self.displayLink invalidate];
self.displayLink = nil;
}
}
- (void)viewDidLoad {
[super viewDidLoad];
self.view.backgroundColor = [UIColor blackColor];
/*
整体思路:
和GLSL加载图片的流程一样
不同分屏滤镜效果,主要是在着色器里去计算的
这里加一个计时器的关键点在于,让屏幕保持一直刷新渲染,方便切换滤镜及时刷新。更多是用于有动效的滤镜
*/
//1、创建底部切换bar
[self setupFilterBar];
//2、GLSL加载图片流程
[self loaderImage];
//3、启动定时器,刷新屏幕
[self startRender];
}
#pragma mark - 1
- (void)setupFilterBar {
CGFloat filterBarWidth = [UIScreen mainScreen].bounds.size.width;
CGFloat filterBarHeight = 100;
CGFloat filterBarY = [UIScreen mainScreen].bounds.size.height - filterBarHeight;
NSArray *dataSource = @[@"无",@"缩放",@"灵魂出窍",@"抖动",@"闪白",@"毛刺",@"幻觉"];
FilterBar *filerBar = [[FilterBar alloc] initWithFrame:CGRectMake(0, filterBarY, filterBarWidth, filterBarHeight)];
filerBar.itemList = dataSource;
filerBar.delegate = self;
[self.view addSubview:filerBar];
}
- (void)filterBar:(FilterBar *)filterBar didScrollToIndex:(NSUInteger)index {
//1\. 选择默认shader
if (index == 0) {
[self setUpDrawShaderWith:@"normal"];
}else if(index == 1)
{
[self setUpDrawShaderWith:@"scale"];
}else if(index == 2)
{
[self setUpDrawShaderWith:@"soulOut"];
}else if(index == 3)
{
[self setUpDrawShaderWith:@"shake"];
}else if(index == 4)
{
[self setUpDrawShaderWith:@"shineWhite"];
}else if(index == 5)
{
[self setUpDrawShaderWith:@"glitch"];
}else if(index == 6){
[self setUpDrawShaderWith:@"vertigo"];
}
// 重新开始滤镜动画
[self startRender];
}
#pragma mark - 2
- (void)loaderImage {
//1、准备工作
/*
把一些会重复用到的地方,封装起来,然后剩下的不变的,放在这个方法里面。
上下文&设置当前
设置图层
设置缓冲区
设置视口
设置顶点数据
设置顶点缓冲区
解压图片,拿到纹理id(因为这里面只有一个纹理,如果有多个也要拆分出去,方便复用)
*/
[self setUpConfig];
//2、绘制每一个着色器都需要调用的方法。第一次加载,肯定使用默认着色器
/*
1、加载、编译shader
1)拿到shader路径,转成c字符串
2)创建shader对象
3)把着色器字符串 附着到shader对象上
4)编译shader对象&检验
2、附着、连接program
1)创建一个program对象
2)把顶点、片元shader 附着上
3)链接program&检验
3、use program
4、传递数据
1)顶点坐标数据
2)纹理坐标数据
3)采样器传递纹理id(纹理id在准备工作就拿到了,不放这里是防止重复操作)
*/
[self setUpDrawShaderWith:@"normal"];
}
#pragma mark - 2.1
- (void)setUpConfig {
//1.上下文
self.context = [[EAGLContext alloc] initWithAPI: kEAGLRenderingAPIOpenGLES2];
[EAGLContext setCurrentContext:self.context];
//2、图层-设置一个正方形
CAEAGLLayer *layer = [[CAEAGLLayer alloc] init];
layer.frame = CGRectMake(0, 100, self.view.frame.size.width, self.view.frame.size.width);
layer.contentsScale = [[UIScreen mainScreen] scale];
[self.view.layer addSublayer:layer];
//3、缓冲区
//1)渲染缓冲区
GLuint rBuffer,fBuffer;
glGenRenderbuffers(1, &rBuffer);
glBindRenderbuffer(GL_RENDERBUFFER, rBuffer);
//把layer的存储绑定到渲染缓冲区
[self.context renderbufferStorage:GL_RENDERBUFFER fromDrawable:layer];
//2)帧缓冲区
glGenFramebuffers(1, &fBuffer);
glBindFramebuffer(GL_FRAMEBUFFER, fBuffer);
//把renderBuffer绑定到ATTACHMENT0上
glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_RENDERBUFFER, rBuffer);
//4、视口
glViewport(0, 0, self.drawableWidth, self.drawableHeight);
//5、顶点数据
//1)开辟顶点数组内存空间
self.vertices = malloc(sizeof(SenceVertex) * 4);
//2)
self.vertices[0] = (SenceVertex){{-1, 1, 0}, {0, 1}};
self.vertices[1] = (SenceVertex){{-1, -1, 0}, {0, 0}};
self.vertices[2] = (SenceVertex){{1, 1, 0}, {1, 1}};
self.vertices[3] = (SenceVertex){{1, -1, 0}, {1, 0}};
//6、顶点缓冲区
GLuint vBuffer;
glGenBuffers(1, &vBuffer);
glBindBuffer(GL_ARRAY_BUFFER, vBuffer);
glBufferData(GL_ARRAY_BUFFER, sizeof(SenceVertex) * 4, self.vertices, GL_STATIC_DRAW);
//保存,退出的时候才释放
self.vertexBuffer = vBuffer;
//7、解压图片,获取纹理id
GLuint textureID = [self createTextureWithImageName:@"mark.jpeg"];
//设置纹理ID
self.textureID = textureID;
}
- (GLuint)createTextureWithImageName:(NSString *)imageName{
//1、拿到图片路径
//这么写的好处是,图片不做缓存处理
NSString *imagePath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:imageName];
UIImage *image = [UIImage imageWithContentsOfFile:imagePath];
//2、解压图片
CGImageRef imageRef = [image CGImage];
//3、判断图片有没有拿到
if (!imageRef) {
NSLog(@"load image faile");
exit(1);
}
//4、创建上下文
//1)获取宽高
GLuint width = (GLuint)CGImageGetWidth(imageRef);
GLuint height = (GLuint)CGImageGetHeight(imageRef);
//2)拿到图片大小
void *imageData = malloc(width * height * 4);
//3)拿到图片的颜色
CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
//3)上下文
/*
参数1:data,指向要渲染的绘制图像的内存地址
参数2:width,bitmap的宽度,单位为像素
参数3:height,bitmap的高度,单位为像素
参数4:bitPerComponent,内存中像素的每个组件的位数,比如32位RGBA,就设置为8
参数5:bytesPerRow,bitmap的没一行的内存所占的比特数
参数6:colorSpace,bitmap上使用的颜色空间 kCGImageAlphaPremultipliedLast:RGBA
*/
CGContextRef imageContext = CGBitmapContextCreate(imageData, width, height, 8, width * 4, colorSpace, kCGImageAlphaPremultipliedLast | kCGBitmapByteOrder32Big);
//5、重新绘制
CGRect rect = CGRectMake(0, 0, width, height);
//1)翻转策略
CGContextTranslateCTM(imageContext, 0, height);
CGContextScaleCTM(imageContext, 1.0f, -1.0f);
//2)对图片重新绘制,得到一张新的解压后的位图
CGContextDrawImage(imageContext, rect, imageRef);
//3)用完之后释放
CGColorSpaceRelease(colorSpace);
CGContextRelease(imageContext);
//6、设置纹理 (因为这个方法需要我们返回一个id,就不穿默认0了,还是写一遍代码吧)
GLuint textureId;
glGenTextures(1, &textureId);
glBindTexture(GL_TEXTURE_2D, textureId);
//7、载入纹理数据
/*
参数1:纹理模式,GL_TEXTURE_1D、GL_TEXTURE_2D、GL_TEXTURE_3D
参数2:加载的层次,一般设置为0
参数3:纹理的颜色值GL_RGBA
参数4:宽
参数5:高
参数6:border,边界宽度
参数7:format
参数8:type
参数9:纹理数据
*/
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, imageData);
//8、设置纹理属性
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
//9、重新绑定一下(用的时候就绑定准没错)
glBindTexture(GL_TEXTURE_2D, textureId);
//10、释放
free(imageData);
return textureId;
}
#pragma mark - 2.2
- (void)setUpDrawShaderWith:(NSString *)shaderName{
//1\. 编译顶点着色器/片元着色器
GLuint vertexShader = [self compileShaderWithName:shaderName type:GL_VERTEX_SHADER];
GLuint fragmentShader = [self compileShaderWithName:shaderName type:GL_FRAGMENT_SHADER];
//2、
//1)创建一个program
GLuint program = glCreateProgram();
//2)附着
glAttachShader(program, vertexShader);
glAttachShader(program, fragmentShader);
// glDeleteShader(vertexShader);
// glDeleteShader(fragmentShader);
//3)link
glLinkProgram(program);
//4)检查
GLint linkStatus;
glGetProgramiv(program, GL_LINK_STATUS, &linkStatus);
if (linkStatus == GL_FALSE) {
GLchar messages[256];
glGetProgramInfoLog(program, sizeof(messages), 0, &messages[0]);
NSString *messageString = [NSString stringWithUTF8String:messages];
NSLog(@"program链接失败:%@", messageString);
exit(1);
}
//3、use
glUseProgram(program);
//4、传递数据
//1)先拿到通道名
//顶点坐标
GLuint positionSlot = glGetAttribLocation(program, "Position");
//纹理坐标
GLuint textureCoordsSlot = glGetAttribLocation(program, "TextureCoords");
//纹理
GLuint textureSlot = glGetUniformLocation(program, "Texture");
//2)传顶点坐标
glEnableVertexAttribArray(positionSlot);
glVertexAttribPointer(positionSlot, 3, GL_FLOAT, GL_FALSE, sizeof(SenceVertex), NULL + offsetof(SenceVertex, positionCoord));
//3)传纹理坐标
glEnableVertexAttribArray(textureCoordsSlot);
glVertexAttribPointer(textureCoordsSlot, 2, GL_FLOAT, GL_FALSE, sizeof(SenceVertex), NULL + offsetof(SenceVertex, textureCoord));
//4) 传纹理
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, self.textureID);
glUniform1i(textureSlot, 0);
//5.保存program,界面销毁则释放
self.program = program;
}
//编译shader代码
- (GLuint)compileShaderWithName:(NSString *)name type:(GLenum)shaderType {
//1、获得shader路径
NSString *shaderPath = [[NSBundle mainBundle] pathForResource:name ofType:shaderType == GL_VERTEX_SHADER ? @"vsh" : @"fsh"];
//2、转换成c语言字符串
NSError *error;
NSString *shaderString = [NSString stringWithContentsOfFile:shaderPath encoding:NSUTF8StringEncoding error:&error];
if (!shaderString) {
NSLog( @"读取shader失败");
exit(1);
}
// const GLchar* source = (GLchar*)[pathString UTF8String];
const char *shaderStringUTF8 = [shaderString UTF8String];
int shaderStringLength = (int)[shaderString length];
//3、创建shader对象
GLuint shader = glCreateShader(shaderType);
//4、附着
glShaderSource(shader, 1, &shaderStringUTF8, &shaderStringLength);
//5、编译
glCompileShader(shader);
//6、检查编译
GLint compileStatus;
glGetShaderiv(shader, GL_COMPILE_STATUS, &compileStatus);
if (compileStatus == GL_FALSE) {
GLchar messages[256];
glGetShaderInfoLog(shader, sizeof(messages), 0, &messages[0]);
NSString *messageString = [NSString stringWithUTF8String:messages];
NSLog(@"shader编译失败:%@", messageString);
exit(1);
}
return shader;
}
#pragma mark - 3
- (void)startRender {
//1.因为会重复调用,严谨一点,先判断一下
if (self.displayLink) {
[self.displayLink invalidate];
self.displayLink = nil;
}
//2\. 设置displayLink 的方法
self.startTimeInterval = 0;
self.displayLink = [CADisplayLink displayLinkWithTarget:self selector:@selector(timeAction)];
//3.将displayLink 添加到runloop 运行循环
[self.displayLink addToRunLoop:[NSRunLoop mainRunLoop] forMode:NSRunLoopCommonModes];
}
- (void)timeAction{
//DisplayLink 的当前时间撮
if (self.startTimeInterval == 0) {
self.startTimeInterval = self.displayLink.timestamp;
}
//使用program
glUseProgram(self.program);
//绑定buffer
glBindBuffer(GL_ARRAY_BUFFER, self.vertexBuffer);
// 传入时间
CGFloat currentTime = self.displayLink.timestamp - self.startTimeInterval;
GLuint time = glGetUniformLocation(self.program, "Time");
glUniform1f(time, currentTime);
// 清除画布
glClear(GL_COLOR_BUFFER_BIT);
glClearColor(1, 1, 1, 1);
// 重绘
glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
//渲染到屏幕上
[self.context presentRenderbuffer:GL_RENDERBUFFER];
}
//获取渲染缓存区的宽
- (GLint)drawableWidth {
GLint backingWidth;
glGetRenderbufferParameteriv(GL_RENDERBUFFER, GL_RENDERBUFFER_WIDTH, &backingWidth);
return backingWidth;
}
//获取渲染缓存区的高
- (GLint)drawableHeight {
GLint backingHeight;
glGetRenderbufferParameteriv(GL_RENDERBUFFER, GL_RENDERBUFFER_HEIGHT, &backingHeight);
return backingHeight;
}
@end