FresnelShader.js 2.0 KB

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