FresnelShader.js 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. ( function () {
  2. /**
  3. * Based on Nvidia Cg tutorial
  4. */
  5. const FresnelShader = {
  6. uniforms: {
  7. 'mRefractionRatio': {
  8. value: 1.02
  9. },
  10. 'mFresnelBias': {
  11. value: 0.1
  12. },
  13. 'mFresnelPower': {
  14. value: 2.0
  15. },
  16. 'mFresnelScale': {
  17. value: 1.0
  18. },
  19. 'tCube': {
  20. value: null
  21. }
  22. },
  23. vertexShader: `uniform float mRefractionRatio;
  24. uniform float mFresnelBias;
  25. uniform float mFresnelScale;
  26. uniform float mFresnelPower;
  27. varying vec3 vReflect;
  28. varying vec3 vRefract[3];
  29. varying float vReflectionFactor;
  30. void main() {
  31. vec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );
  32. vec4 worldPosition = modelMatrix * vec4( position, 1.0 );
  33. vec3 worldNormal = normalize( mat3( modelMatrix[0].xyz, modelMatrix[1].xyz, modelMatrix[2].xyz ) * normal );
  34. vec3 I = worldPosition.xyz - cameraPosition;
  35. vReflect = reflect( I, worldNormal );
  36. vRefract[0] = refract( normalize( I ), worldNormal, mRefractionRatio );
  37. vRefract[1] = refract( normalize( I ), worldNormal, mRefractionRatio * 0.99 );
  38. vRefract[2] = refract( normalize( I ), worldNormal, mRefractionRatio * 0.98 );
  39. vReflectionFactor = mFresnelBias + mFresnelScale * pow( 1.0 + dot( normalize( I ), worldNormal ), mFresnelPower );
  40. gl_Position = projectionMatrix * mvPosition;
  41. }`,
  42. fragmentShader: `uniform samplerCube tCube;
  43. varying vec3 vReflect;
  44. varying vec3 vRefract[3];
  45. varying float vReflectionFactor;
  46. void main() {
  47. vec4 reflectedColor = textureCube( tCube, vec3( -vReflect.x, vReflect.yz ) );
  48. vec4 refractedColor = vec4( 1.0 );
  49. refractedColor.r = textureCube( tCube, vec3( -vRefract[0].x, vRefract[0].yz ) ).r;
  50. refractedColor.g = textureCube( tCube, vec3( -vRefract[1].x, vRefract[1].yz ) ).g;
  51. refractedColor.b = textureCube( tCube, vec3( -vRefract[2].x, vRefract[2].yz ) ).b;
  52. gl_FragColor = mix( refractedColor, reflectedColor, clamp( vReflectionFactor, 0.0, 1.0 ) );
  53. }`
  54. };
  55. THREE.FresnelShader = FresnelShader;
  56. } )();