MatCap && Cocos Creator Shader
在某些層面能替代PBR的次世代渲染方案。
效果
動圖

視頻
https://www.bilibili.com/video/BV1B64y147xc
實現(xiàn)
實現(xiàn)原理是,用一張?zhí)刂频募y理圖(采樣出來的紋理),加上一段shader代碼(法向量映射紋理),模擬出次世代的效果(場景中無需光照)。

代碼
參考 https://github.com/nidorx/matcaps 中的核心代碼,在 Cocos Creator 3.1.0 中實現(xiàn)的effect代碼如下。
CCEffect %{
techniques:
- name: opaque
passes:
- vert: unlit-vs:vert # builtin header
frag: unlit-fs:frag
properties: &props
mainTexture: { value: white }
- name: transparent
passes:
- vert: unlit-vs:vert # builtin header
frag: unlit-fs:frag
blendState:
targets:
- blend: true
blendSrc: src_alpha
blendDst: one_minus_src_alpha
blendSrcAlpha: src_alpha
blendDstAlpha: one_minus_src_alpha
properties: *props
}%
CCProgram unlit-vs %{
precision highp float;
#include <input-standard>
#include <cc-global>
#include <cc-local-batch>
out vec2 v_uv;
out vec3 v_normal;
vec4 vert () {
StandardVertInput In;
CCVertInput(In);
vec4 position = In.position;
mat4 matWorld, matWorldIT;
CCGetWorldMatrixFull(matWorld, matWorldIT);
v_normal = normalize((matWorldIT * vec4(In.normal.xyz, 0.0)).xyz);
v_uv = a_texCoord;
return cc_matProj * (cc_matView * matWorld) * position;
}
}%
CCProgram unlit-fs %{
precision highp float;
#include <output>
#include <cc-global>
in vec2 v_uv;
in vec3 v_normal;
uniform sampler2D mainTexture;
vec4 frag () {
highp vec2 muv = vec2(cc_matView * vec4(normalize(v_normal), 0))*0.5+vec2(0.5,0.5);
// read texture inverting Y value
vec4 col = texture(mainTexture, vec2(muv.x, 1.0-muv.y));
return CCFragOutput(col);
}
}%
關(guān)于如何移植shader代碼,可參考上一篇文章《如何抄一個 shader 到 Cocos Creator》
MatCap
MatCap (Material Capture) 是一個包含了光照和反射等信息的貼圖,運行時使用法線方向進行采樣。

MatCap 有以下幾個特點
無需光照的計算,運行效率高。 對于同一材質(zhì),只需一個紋理球貼圖,貼圖通用。 因為光照是寫在貼圖里的,不適合精準光照的情況(例如旋轉(zhuǎn)攝像機角度)。

對于法向量紋理映射方法,在https://github.com/nidorx/matcaps中使用的是法向量的x,y值。(本demo也是采用這種實現(xiàn)方式)
在相機空間下的物體法線,可以不考慮Z軸。因為法線是一個單位向量,如果法線在XY方向上的投影權(quán)重很大,那么說明在Z方向的權(quán)重就很小,對應到二維的MatCap上采樣的位置越靠近邊緣;而如果法線在XY方向的投影權(quán)重很小,那么Z方向的權(quán)重就很大,對應到二維的MatCap上的采樣位置就越靠近中心。

在https://www.clicktorelease.com/blog/creating-spherical-environment-mapping-shader/介紹了一種基于反射向量的實現(xiàn)。

既可以逐頂點實現(xiàn),也可逐像素實現(xiàn),參考代碼如下。

有幾張方法可以制作 MatCap 貼圖
3d建模軟件 用游戲引擎渲染 真實相機拍攝 藝術(shù)家手繪

小結(jié)
完整代碼工程:https://github.com/baiyuwubing/cocos-creator-examples/tree/master/awesome-shader
以上為白玉無冰使用 Cocos Creator 3.1.0 實現(xiàn) "MatCap Shader" 的技術(shù)分享。
擴展閱讀
https://github.com/nidorx/matcaps
https://www.clicktorelease.com/blog/creating-spherical-environment-mapping-shader/
https://medium.com/playkids-tech-blog/matcap-render-art-pipeline-optimization-for-mobile-devices-4e1a520b9f1a
https://zhuanlan.zhihu.com/p/347947799
https://zhuanlan.zhihu.com/p/27339998
更多
點擊“閱讀原文”查看精選導航
“點贊“ ”在看” 鼓勵一下
▼
