three.js examples (threejs.org)
顶点着色器
attribute vec3 position; //顶点
uniform mat4 modelMatrix;//模型矩阵
varying vec3 vWorldDirection;
void main() {
vWorldDirection = transformDirection( position, modelMatrix ); //相对于0,0,0的向量 世界方向
vec3 transformed = vec3( position );
vec4 mvPosition = vec4( transformed, 1.0 );
#ifdef USE_INSTANCING //没用上
mvPosition = instanceMatrix * mvPosition;
#endif
mvPosition = modelViewMatrix * mvPosition; //视口空间了
gl_Position = projectionMatrix * mvPosition; //投影空间了
gl_Position.z = gl_Position.w; //视口空间的z值 片元着色器里 这个会被w为变为1
}
vec3 transformDirection( in vec3 dir, in mat4 matrix ) {
return normalize( ( matrix * vec4( dir, 0.0 ) ).xyz );
}
片元着色器
#ifdef USE_ENVMAP
uniform float envMapIntensity;
uniform float flipEnvMap; //-1
uniform int maxMipLevel;
#ifdef ENVMAP_TYPE_CUBE
uniform samplerCube envMap;
#else
uniform sampler2D envMap;
#endif
#endif
void main() {
vec3 vReflect = vWorldDirection; //世界方向
#ifdef USE_ENVMAP //设置了环境图
#ifdef ENV_WORLDPOS //没有这个
vec3 cameraToFrag;
if ( isOrthographic ) {
cameraToFrag = normalize( vec3( - viewMatrix[ 0 ][ 2 ], - viewMatrix[ 1 ][ 2 ], - viewMatrix[ 2 ][ 2 ] ) );
}
else {
cameraToFrag = normalize( vWorldPosition - cameraPosition );
}
vec3 worldNormal = inverseTransformDirection( normal, viewMatrix );
#ifdef ENVMAP_MODE_REFLECTION
vec3 reflectVec = reflect( cameraToFrag, worldNormal );
#else
vec3 reflectVec = refract( cameraToFrag, worldNormal, refractionRatio );
#endif
#else
vec3 reflectVec = vReflect; //世界方向
#endif
#ifdef ENVMAP_TYPE_CUBE //
vec4 envColor = textureCube( envMap, vec3( flipEnvMap * reflectVec.x, reflectVec.yz ) );
#elif defined( ENVMAP_TYPE_CUBE_UV ) //没定义
vec4 envColor = textureCubeUV( envMap, reflectVec, 0.0 );
#else
vec4 envColor = vec4( 0.0 );
#endif
#ifndef ENVMAP_TYPE_CUBE_UV //没定义
envColor = envMapTexelToLinear( envColor );
#endif
#ifdef ENVMAP_BLENDING_MULTIPLY //没定义
outgoingLight = mix( outgoingLight, outgoingLight * envColor.xyz, specularStrength * reflectivity );
#elif defined( ENVMAP_BLENDING_MIX )
outgoingLight = mix( outgoingLight, envColor.xyz, specularStrength * reflectivity );
#elif defined( ENVMAP_BLENDING_ADD )
outgoingLight += envColor.xyz * specularStrength * reflectivity;
#endif
#endif
gl_FragColor = envColor;
gl_FragColor.a *= opacity;
#if defined( TONE_MAPPING ) //hdr
gl_FragColor.rgb = toneMapping( gl_FragColor.rgb );
#endif
gl_FragColor = linearToOutputTexel( gl_FragColor );
}