前面两篇分别讲了Three.js的源码结构和Shader改写方法,本篇做一个基于Standard材质的菲涅尔。
如未读过前两篇的建议先读一下:
Three.js Shader源码结构https://www.jianshu.com/p/8de8a94ac1a9
Three.js Shader改写https://www.jianshu.com/p/5944e10d70cf
仅打开一盏平行光时最终效果如下,可以看到在原有兰伯特的基础上增加了由外向内的菲涅尔效果:
1.改写前准备
参考前面两篇,我们的目标是改写StandardMaterial,所以我们要找到StandardMaterial的源码。打开Three.js的源码,我们发现如下两行定义了StandardMaterial的vertexShader和fragmentShader。
- standard: {
-
- uniforms: mergeUniforms([
- ...略
- ]),
-
- vertexShader: ShaderChunk.meshphysical_vert,
- fragmentShader: ShaderChunk.meshphysical_frag
-
- },
顺藤摸瓜找到meshphysical_frag指向的是fragment$5:
- meshphysical_vert: vertex$5,
- meshphysical_frag: fragment$5,
而fragment$5最后用到的include是:
#include <dithering_fragment>
所以我们要在最后修改颜色的话,就得replace这句话。下面这段代码就实现了一个球的菲涅尔,至于菲涅尔的算法1-NdotV这里就不赘述了。
- const geometry1 = new THREE.SphereGeometry(0.2, 32, 16);
- const material1 = new THREE.MeshStandardMaterial({ color: 0xffffff });
- const sphere1 = new THREE.Mesh(geometry1, material1);
- scene.add(sphere1);
- sphere1.position.y = 0.5;
-
- let uniforms = {
- rimColor: { value: new THREE.Color(0xff00ff) },
- rimPower: { value: 0.6 },
- }
- sphere1.material.onBeforeCompile = function (shader) {
- shader.uniforms.rimColor = uniforms.rimColor;
- shader.uniforms.rimPower = uniforms.rimPower;
-
- shader.fragmentShader = /* glsl */`
- uniform vec3 rimColor;
- uniform float rimPower;
- ${shader.fragmentShader.replace(
- '#include <dithering_fragment>',
- '#include <dithering_fragment>\n\tfloat dotNV = 1.0-saturate( dot( normal, geometry.viewDir ) );\n\tgl_FragColor.rgb += rimPower*dotNV*rimColor;'
- )}
- `;
- };
加载的模型的材质改写也很简单,遍历所有子物体,如果isMesh则执行.material.onBeforeCompile。