Metal与图形渲染十:动态滤镜

零. 前言

提起图形渲染技术,大家的第一时间应该是各种各样的滤镜,而几年前抖音能得以迅速扩张,能整出各种花活的滤镜自然是功臣之一,今天来用Metal做几个滤镜玩玩~

一. 缩放

缩放滤镜是通过顶点着色器实现的,原理是随着时间推移,将顶点坐标放大/缩小,使用sin函数得到平滑的效果,我们将时间戳等分为1000小份,用sin函数将放大系数限制在[1, 1.1]区间:

constant int smooth = 1000;

vertex SingleInputVertexIO
zoomVertex(const device float2 *position [[ buffer(0) ]],
           const device float &currentTime [[ buffer(1) ]],
           const device float2 *textureCoord [[ buffer(2) ]],
           uint vid [[ vertex_id ]]) {
    SingleInputVertexIO out;
    
    long tick = ((long)(currentTime * smooth)) % smooth;
    
    float freq = 1.0 / smooth * tick;
    
    float maxAmplitude = 0.1;
    
    // 将顶点坐标放大
    float amplitude = 1.0 + maxAmplitude * max(sin(freq * M_PI_F * 2), 0.0);
    
    float2 currentPos = amplitude * position[vid];
    
    out.position = float4(currentPos, 0, 1);
    out.textureCoordinate = textureCoord[vid];
    
    return out;
}

二. 旋转

旋转效果同样也修改到了顶点着色器,原理同样是根据时间,修改顶点x、y坐标,只不过这次x用sin函数,y用cos函数了。

vertex SingleInputVertexIO
rotateVertex(const device float2 *position [[ buffer(0) ]],
             const device float &currentTime [[ buffer(1) ]],
             const device float2 *textureCoord [[ buffer(2) ]],
             uint vid [[ vertex_id ]]) {
    SingleInputVertexIO out;
    
    float speed = 0.5;
    
    long tick = ((long)((currentTime * speed) * smooth)) % smooth;
    
    float freq = 1.0 / smooth * tick;
    
    float maxAmplitude = 0.1;
    float amplitudeX = maxAmplitude * sin(freq * M_PI_F * 2);
    float amplitudeY = maxAmplitude * cos(freq * M_PI_F * 2);

    float2 currentPos = position[vid] + float2(amplitudeX, amplitudeY);
    
    out.position = float4(currentPos, 0, 1);
    out.textureCoordinate = textureCoord[vid];
    
    return out;
}

三. 灵魂出窍

灵魂出窍效果的原理是将放大后的纹理和原纹理进行颜色的混合,随着时间推移,纹理会越来越大,但是透明度会越来越小,通过修改片段着色器实现:

fragment float4
soulOutFragment(SingleInputVertexIO input [[ stage_in ]],
                texture2d <float> texture [[ texture(0) ]],
                constant float &currentTime [[ buffer(0) ]]) {
    
    long tick = ((long)(currentTime * smooth)) % smooth;

    // [0, 1], progress越大,图片越大,但越透明
    float progress = 1.0 / smooth * tick;
    
    float maxAlpha = 0.4;
    
    float maxScale = 1.8;
    
    float alpha = maxAlpha * (1.0 - progress);
    
    float scale = 1.0 + (maxScale - 1.0) * progress;
    
    float2 textureCoor = input.textureCoordinate;
    
    // scale越大,纹理采样坐标越靠近中心点,达到放大图像的效果
    float2 maskCoor = float2(0.5, 0.5) + (textureCoor - 0.5) / scale;
    
    constexpr sampler textureSampler;
    
    float4 maskColor = texture.sample(textureSampler, maskCoor);
    float4 originColor = texture.sample(textureSampler, textureCoor);
    
    return mix(originColor, maskColor, alpha);
}

四. 颜色抖动

颜色抖动的原理是将原纹理的r值和g值分别向左上、右下偏移,而b值、a值则取原纹理的值,通过片段着色器实现:

fragment float4
colorShakeFragment(SingleInputVertexIO input [[ stage_in ]],
                   texture2d <float> texture [[ texture(0) ]],
                   constant float &currentTime [[ buffer(0) ]]) {
    
    long tick = ((long)(currentTime * smooth)) % smooth;

    float freq = 1.0 / smooth * tick;
        
    float maxScale = 0.01;
    
    float2 textureCoor = input.textureCoordinate;
    
    float2 offset = maxScale * max(sin(freq * M_PI_F * 2), 0.0);
    
    constexpr sampler textureSampler;
    
    float maskColorR = texture.sample(textureSampler, textureCoor - offset).r;
    float maskColorG = texture.sample(textureSampler, textureCoor + offset).g;
    float4 originColor = texture.sample(textureSampler, textureCoor);
    
    return float4(maskColorR, maskColorG, originColor.ba);
}

五. 毛刺效果

毛刺效果的原理是,对于纹理的同一行像素,让其随机向左右偏移,但是为了让原图像能被辨别出来,采取了少量像素大偏移、大量像素小偏移的策略,为了有色差的感觉,再将r、g、b分开偏移计算。

值得一提的是,为了获取随机数,使用了fract(sin(x) * 43758.5453123)这个奇怪的公式,但这串奇怪的数字看起来好经典的样子,能得到电视雪花屏的随机效果。

// 获得一个[0, 1]的随机数,https://xiaoiver.github.io/coding/2018/08/01/%E5%99%AA%E5%A3%B0%E7%9A%84%E8%89%BA%E6%9C%AF.html
float rand(float x) {
    return fract(sin(x) * 43758.5453123);
}

fragment float4
jitterFragment(SingleInputVertexIO input [[ stage_in ]],
               texture2d<float> texture [[ texture(0) ]],
               constant float &currentTime [[ buffer(0) ]]) {
    long tick = ((long)(currentTime * smooth)) % smooth;
    
    float freq = 1.0 / smooth * tick;
    
    // [0, 1], 振幅
    float amplitude = max(sin(freq * M_PI_F * 2), 0.0);
    
    // 最大抖动
    float maxJitter = 0.06;
    
    float3 rgbOffset = float3(0.01, 0.02, -0.03) * amplitude;
    
    float2 textureCoor = input.textureCoordinate;
    
    // [-1, 1]的随机像素偏移
    float jitter = rand(textureCoor.y) * 2 - 1.0;
    
    bool needOffset = abs(jitter) < maxJitter * amplitude;
    
    // 根据x坐标和needOffset计算x撕裂
    // 当needOffset为true,撕裂大
    // 当needOffset为false,撕裂小
    // 绝大部分的行会撕裂小,少量的会撕裂大
    float textureX = textureCoor.x + (needOffset ? jitter : jitter * amplitude * 0.006);
    
    float2 maskCoorR = float2(textureX + rgbOffset.r, textureCoor.y);
    float2 maskCoorG = float2(textureX + rgbOffset.g, textureCoor.y);
    float2 maskCoorB = float2(textureX + rgbOffset.b, textureCoor.y);

    constexpr sampler textureSampler;
    
    float maskR = texture.sample(textureSampler, maskCoorR).r;
    float maskG = texture.sample(textureSampler, maskCoorG).g;
    float maskB = texture.sample(textureSampler, maskCoorB).b;
    float4 originColor = texture.sample(textureSampler, textureCoor);
    
    return float4(maskR, maskG, maskB, originColor.a);
}

六. 闪白效果

闪白效果的原理是随着时间推移,将白色色值和纹理色值进行不同程度的混合,比较简单:

fragment float4
flashFragment(SingleInputVertexIO input [[ stage_in ]],
              texture2d <float> texture [[ texture(0) ]],
              constant float &currentTime [[ buffer(0) ]]) {
    long tick = ((long)(currentTime * smooth)) % smooth;
    float freq = 1.0 / smooth * tick;
    
    float progress = max(sin(freq * M_PI_F * 2), 0.0);
    
    constexpr sampler textureSampler;
    float4 originColor = texture.sample(textureSampler, input.textureCoordinate);
    float4 whiteColor = float4(1.0, 1.0, 1.0, 1.0);
    
    return mix(originColor, whiteColor, progress);
}

七. 滤镜的叠加和删除

滤镜链的初始状态为Picture => RenderView

当需要添加链时,修改结构为Picture => 原有Filter =>... => newFilter => RenderView,将需要添加的Filter指向RenderView,再将原指向RenderView的结构指向新增的Filter。

当需要删除链时,修改结构为Picture => 原有Filter => ... => RenderView,将原指向Filter的结构指向Filter的下一级。

其实就是链表的插入和删除,哈哈

- (void)changeTargetStatus:(HobenMetalFilter *)target insert:(BOOL)insert {
    if (![self.picture.targets[0] isKindOfClass:[HobenMetalFilter class]]) {
        if (insert) {
            [self.picture removeTarget:self.renderView];
            [self.picture addTarget:target];
            [target addTarget:self.renderView];
        }
        return;
    }
    HobenMetalFilter *cur = (HobenMetalFilter *)self.picture.targets[0];
    
    HobenMetalOutput *pre = self.picture;
    
    while ([cur.targets[0] isKindOfClass:[HobenMetalFilter class]] && ![cur isEqual:target]) {
        pre = cur;
        cur = (HobenMetalFilter *)cur.targets[0];
    }
    
    if (insert) {
        // 插入
        [pre removeTarget:cur];
        [pre addTarget:target];
        [target addTarget:cur];
    } else {
        // 删除
        [pre removeTarget:target];
        [pre addTarget:cur.targets[0]];
        [target removeAllTargets];
    }
}

最后在每一帧调用的时候都给Filter们传入当前的时间戳就可以啦~

- (void)drawInMTKView:(MTKView *)view {
    float currentTime = [[NSDate date] timeIntervalSince1970] - self.startTime;
    
    [[self filters] makeObjectsPerformSelector:@selector(setCurrentTime:) withObject:@(currentTime)];
        
    [self.picture processImage];
}

八. 总结

酷炫的滤镜的产生,离不开顶点着色器和片段着色器,当我们需要对纹理本身进行一些位置的变化时,一般修改的是顶点着色器(当然,将片段着色器的纹理坐标放缩也能达到效果);当我们需要对纹理一些颜色进行处理、或者是基于原有纹理进行一些颜色的混合时,一般修改的是片段着色器。

如果需要颜色分离,不妨考虑下将R、G、B三个通道的值赋予不同的offset,会有一些惊艳的效果产生。

当前已经实现的Metal滤镜链支持不同滤镜的叠加和删除,后续的优化方向可以考虑加入某些时间点使用哪些滤镜的操作,用户可以自行对滤镜进行时间上和效果上的调整,对原素材进行剪辑,会使得滤镜可玩性更高。

九. 参考

OpenGL ES案例-抖音系滤镜实现

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 216,544评论 6 501
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 92,430评论 3 392
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 162,764评论 0 353
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,193评论 1 292
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,216评论 6 388
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,182评论 1 299
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,063评论 3 418
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 38,917评论 0 274
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,329评论 1 310
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,543评论 2 332
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,722评论 1 348
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,425评论 5 343
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,019评论 3 326
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,671评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,825评论 1 269
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 47,729评论 2 368
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,614评论 2 353

推荐阅读更多精彩内容