FresnelShader.js 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  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:
  24. /* glsl */
  25. `
  26. uniform float mRefractionRatio;
  27. uniform float mFresnelBias;
  28. uniform float mFresnelScale;
  29. uniform float mFresnelPower;
  30. varying vec3 vReflect;
  31. varying vec3 vRefract[3];
  32. varying float vReflectionFactor;
  33. void main() {
  34. vec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );
  35. vec4 worldPosition = modelMatrix * vec4( position, 1.0 );
  36. vec3 worldNormal = normalize( mat3( modelMatrix[0].xyz, modelMatrix[1].xyz, modelMatrix[2].xyz ) * normal );
  37. vec3 I = worldPosition.xyz - cameraPosition;
  38. vReflect = reflect( I, worldNormal );
  39. vRefract[0] = refract( normalize( I ), worldNormal, mRefractionRatio );
  40. vRefract[1] = refract( normalize( I ), worldNormal, mRefractionRatio * 0.99 );
  41. vRefract[2] = refract( normalize( I ), worldNormal, mRefractionRatio * 0.98 );
  42. vReflectionFactor = mFresnelBias + mFresnelScale * pow( 1.0 + dot( normalize( I ), worldNormal ), mFresnelPower );
  43. gl_Position = projectionMatrix * mvPosition;
  44. }`,
  45. fragmentShader:
  46. /* glsl */
  47. `
  48. uniform samplerCube tCube;
  49. varying vec3 vReflect;
  50. varying vec3 vRefract[3];
  51. varying float vReflectionFactor;
  52. void main() {
  53. vec4 reflectedColor = textureCube( tCube, vec3( -vReflect.x, vReflect.yz ) );
  54. vec4 refractedColor = vec4( 1.0 );
  55. refractedColor.r = textureCube( tCube, vec3( -vRefract[0].x, vRefract[0].yz ) ).r;
  56. refractedColor.g = textureCube( tCube, vec3( -vRefract[1].x, vRefract[1].yz ) ).g;
  57. refractedColor.b = textureCube( tCube, vec3( -vRefract[2].x, vRefract[2].yz ) ).b;
  58. gl_FragColor = mix( refractedColor, reflectedColor, clamp( vReflectionFactor, 0.0, 1.0 ) );
  59. }`
  60. };
  61. THREE.FresnelShader = FresnelShader;
  62. } )();