Blend混合模式 与 20余种颜色混合模式代码实现

https://www.bilibili.com/read/cv1874791

 

【UnityShader】Blend混合模式 与 20余种颜色混合模式代码实现(多图预警)

混合模式

  • 可简单理解为 指上下层图片相互有重叠时如何取色的一种称呼

  • 以下是百科给的解释 但我们今天要说的是Unity中的颜色混合

混合模式是图像处理技术中的一个技术名词,不仅用于广泛使用的Photoshop中,也应用于AfterEffect、llustrator 、 Dreamweaver、 Fireworks等软件。主要功效是可以用不同的方法将对象颜色与底层对象的颜色混合。当您将一种混合模式应用于某一对象时,在此对象的图层或组下方的任何对象上都可看到混合模式的效果。

Blend

  • 在编写shader时我们可以在SubShader或Pass中用Blend与BlendOp指明该对象与下一层色彩如何进行颜色混合

  • 常用的混合模式通过Blend实现 如下所示

混合模式Blend实现
  • 以下为测试图片

测试底图
测试混合图

 

  • 常用的滤色混合效果如下

滤色混合效果

代码实现混合模式

  • 可以看到Blend已经可以实现很多种混合效果 但这也只是混合模式的一部分

  • 而接下来才是重点 我们要在Shader中代码自己实现更多的混合模式

  • 以方便实现更多的Shader效果

  • 框架代码如下 还是前几篇文章一样 只更改frag中代码

混合模式shader框架代码
  • 其中MainTex为底图 BlendTex为要混合的图片

  • 颜色取值为(0-1) A为底图颜色 B为混合图颜色 C为输出图颜色

frag函数代码
  • 使用step()函数来代替if判断    

注意:非常多资料 点光效果 使用两个min函数  实际效果还原应该是一个min一个max函数

所有混合模式代码实现

 

 

Unity实现与Ps效果对比图

  • 创建材质球 给与材质球该shader 将材质球赋给 Image UI 或者 2D Sprite 

  • 添加对应贴图 如下

 

材质球设置

 

  • 查看实验效果(左 Unity实现 右 Ps对比)

 

正常模式
变暗
变亮
正片叠底
滤色
线性加深
线性减淡
叠加
强光
柔光
亮光
点光
线性光
实色混合
排除
差值
深色
浅色
减去
划分

核心代码

        fixed4 C =A*(1-B.a)+B*(B.a);  //正常透明度混合

 

        fixed4 C =min(A,B); //变暗

 

        fixed4 C =max(A,B); //变亮

 

        fixed4 C =A*B ; //正片叠底

 

        fixed4 C=1-((1-A)*(1-B));//滤色 A+B-A*B

 

        fixed4 C =A-((1-A)*(1-B))/B; //颜色加深

 

        fixed4 C= A+(A*B)/(1-B); //颜色减淡

 

        fixed4 C=A+B-1;//线性加深

 

        fixed4 C=A+B; //线性减淡

        

        fixed4 ifFlag= step(A,fixed4(0.5,0.5,0.5,0.5));

        fixed4 C=ifFlag*A*B*2+(1-ifFlag)*(1-(1-A)*(1-B)*2);//叠加

        

        fixed4 ifFlag= step(B,fixed4(0.5,0.5,0.5,0.5));

        fixed4 C=ifFlag*A*B*2+(1-ifFlag)*(1-(1-A)*(1-B)*2); //强光

 

        fixed4 ifFlag= step(B,fixed4(0.5,0.5,0.5,0.5));

        fixed4 C=ifFlag*(A*B*2+A*A*(1-B*2))+(1-ifFlag)*(A*(1-B)*2+sqrt(A)*(2*B-1)); //柔光

        

        fixed4 ifFlag= step(B,fixed4(0.5,0.5,0.5,0.5));

        fixed4 C=ifFlag*(A-(1-A)*(1-2*B)/(2*B))+(1-ifFlag)*(A+A*(2*B-1)/(2*(1-B))); //亮光

 

        fixed4 ifFlag= step(B,fixed4(0.5,0.5,0.5,0.5)); 

        fixed4 C=ifFlag*(min(A,2*B))+(1-ifFlag)*(max(A,( B*2-1))); //点光  

        

        fixed4 C=A+2*B-1; //线性光

 

        fixed4 ifFlag= step(A+B,fixed4(1,1,1,1));

        fixed4 C=ifFlag*(fixed4(0,0,0,0))+(1-ifFlag)*(fixed4(1,1,1,1)); //实色混合

 

        fixed4 C=A+B-A*B*2; //排除

 

        fixed4 C=abs(A-B); //差值

 

        fixed4 ifFlag= step(B.r+B.g+B.b,A.r+A.g+A.b);

        fixed4 C=ifFlag*(B)+(1-ifFlag)*(A); //深色

 

        fixed4 ifFlag= step(B.r+B.g+B.b,A.r+A.g+A.b);

        fixed4 C=ifFlag*(A)+(1-ifFlag)*(B); //浅色

 

        fixed4 C=A-B; //减去

 

        fixed4 C=A/B; //划分



结语

  • 这些公式不用记住 再用到的时候查找挑选合适的方法就好

  • 项目源代码:https://github.com/QinZhuo/ShaderLab

posted @ 2020-01-12 19:23  00000000O  阅读(1253)  评论(0编辑  收藏  举报