Refractor.js 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324
  1. /**
  2. * @author Mugen87 / https://github.com/Mugen87
  3. *
  4. */
  5. THREE.Refractor = function ( width, height, options ) {
  6. THREE.Mesh.call( this, new THREE.PlaneBufferGeometry( width, height ) );
  7. this.type = 'Refractor';
  8. var scope = this;
  9. var color = options.color || new THREE.Color( 0x7f7f7f );
  10. var textureWidth = options.textureWidth || 512;
  11. var textureHeight = options.textureHeight || 512;
  12. var clipBias = options.clipBias || 0;
  13. var shader = options.shader || THREE.DefaultRefractionShader;
  14. //
  15. var virtualCamera = new THREE.PerspectiveCamera();
  16. virtualCamera.matrixAutoUpdate = false;
  17. virtualCamera.userData.refractor = true;
  18. //
  19. var refractorPlane = new THREE.Plane();
  20. var textureMatrix = new THREE.Matrix4();
  21. // render target
  22. var parameters = {
  23. minFilter: THREE.LinearFilter,
  24. magFilter: THREE.LinearFilter,
  25. format: THREE.RGBFormat,
  26. stencilBuffer: false
  27. };
  28. var renderTarget = new THREE.WebGLRenderTarget( textureWidth, textureHeight, parameters );
  29. if ( ! THREE.Math.isPowerOfTwo( textureWidth ) || ! THREE.Math.isPowerOfTwo( textureHeight ) ) {
  30. renderTarget.texture.generateMipmaps = false;
  31. }
  32. // material
  33. this.material = new THREE.ShaderMaterial( {
  34. uniforms: THREE.UniformsUtils.clone( shader.uniforms ),
  35. vertexShader: shader.vertexShader,
  36. fragmentShader: shader.fragmentShader,
  37. transparent: true // ensures, refractors are drawn from farthest to closest
  38. } );
  39. this.material.uniforms.color.value = color;
  40. this.material.uniforms.tDiffuse.value = renderTarget.texture;
  41. this.material.uniforms.textureMatrix.value = textureMatrix;
  42. // functions
  43. var visible = ( function () {
  44. var refractorWorldPosition = new THREE.Vector3();
  45. var cameraWorldPosition = new THREE.Vector3();
  46. var rotationMatrix = new THREE.Matrix4();
  47. var view = new THREE.Vector3();
  48. var normal = new THREE.Vector3();
  49. return function updateRefractorPlane( camera ) {
  50. refractorWorldPosition.setFromMatrixPosition( scope.matrixWorld );
  51. cameraWorldPosition.setFromMatrixPosition( camera.matrixWorld );
  52. view.subVectors( refractorWorldPosition, cameraWorldPosition );
  53. rotationMatrix.extractRotation( scope.matrixWorld );
  54. normal.set( 0, 0, 1 );
  55. normal.applyMatrix4( rotationMatrix );
  56. return view.dot( normal ) < 0;
  57. };
  58. } )();
  59. var updateRefractorPlane = ( function () {
  60. var normal = new THREE.Vector3();
  61. var position = new THREE.Vector3();
  62. var quaternion = new THREE.Quaternion();
  63. var scale = new THREE.Vector3();
  64. return function updateRefractorPlane() {
  65. scope.matrixWorld.decompose( position, quaternion, scale );
  66. normal.set( 0, 0, 1 ).applyQuaternion( quaternion ).normalize();
  67. // flip the normal because we want to cull everything above the plane
  68. normal.negate();
  69. refractorPlane.setFromNormalAndCoplanarPoint( normal, position );
  70. };
  71. } )();
  72. var updateVirtualCamera = ( function () {
  73. var clipPlane = new THREE.Plane();
  74. var clipVector = new THREE.Vector4();
  75. var q = new THREE.Vector4();
  76. return function updateVirtualCamera( camera ) {
  77. virtualCamera.matrixWorld.copy( camera.matrixWorld );
  78. virtualCamera.matrixWorldInverse.getInverse( virtualCamera.matrixWorld );
  79. virtualCamera.projectionMatrix.copy( camera.projectionMatrix );
  80. virtualCamera.far = camera.far; // used in WebGLBackground
  81. // The following code creates an oblique view frustum for clipping.
  82. // see: Lengyel, Eric. “Oblique View Frustum Depth Projection and Clipping”.
  83. // Journal of Game Development, Vol. 1, No. 2 (2005), Charles River Media, pp. 5–16
  84. clipPlane.copy( refractorPlane );
  85. clipPlane.applyMatrix4( virtualCamera.matrixWorldInverse );
  86. clipVector.set( clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.constant );
  87. // calculate the clip-space corner point opposite the clipping plane and
  88. // transform it into camera space by multiplying it by the inverse of the projection matrix
  89. var projectionMatrix = virtualCamera.projectionMatrix;
  90. q.x = ( Math.sign( clipVector.x ) + projectionMatrix.elements[ 8 ] ) / projectionMatrix.elements[ 0 ];
  91. q.y = ( Math.sign( clipVector.y ) + projectionMatrix.elements[ 9 ] ) / projectionMatrix.elements[ 5 ];
  92. q.z = - 1.0;
  93. q.w = ( 1.0 + projectionMatrix.elements[ 10 ] ) / projectionMatrix.elements[ 14 ];
  94. // calculate the scaled plane vector
  95. clipVector.multiplyScalar( 2.0 / clipVector.dot( q ) );
  96. // replacing the third row of the projection matrix
  97. projectionMatrix.elements[ 2 ] = clipVector.x;
  98. projectionMatrix.elements[ 6 ] = clipVector.y;
  99. projectionMatrix.elements[ 10 ] = clipVector.z + 1.0 - clipBias;
  100. projectionMatrix.elements[ 14 ] = clipVector.w;
  101. };
  102. } )();
  103. // This will update the texture matrix that is used for projective texture mapping in the shader.
  104. // see: http://developer.download.nvidia.com/assets/gamedev/docs/projective_texture_mapping.pdf
  105. function updateTextureMatrix( camera ) {
  106. // this matrix does range mapping to [ 0, 1 ]
  107. textureMatrix.set(
  108. 0.5, 0.0, 0.0, 0.5,
  109. 0.0, 0.5, 0.0, 0.5,
  110. 0.0, 0.0, 0.5, 0.5,
  111. 0.0, 0.0, 0.0, 1.0
  112. );
  113. // we use "Object Linear Texgen", so we need to multiply the texture matrix T
  114. // (matrix above) with the projection and view matrix of the virtual camera
  115. // and the model matrix of the refractor
  116. textureMatrix.multiply( camera.projectionMatrix );
  117. textureMatrix.multiply( camera.matrixWorldInverse );
  118. textureMatrix.multiply( scope.matrixWorld );
  119. }
  120. //
  121. var render = ( function () {
  122. var viewport = new THREE.Vector4();
  123. return function render( renderer, scene, camera ) {
  124. scope.visible = false;
  125. var currentRenderTarget = renderer.getRenderTarget();
  126. var currentVrEnabled = renderer.vr.enabled;
  127. var currentShadowAutoUpdate = renderer.shadowMap.autoUpdate;
  128. renderer.vr.enabled = false; // avoid camera modification
  129. renderer.shadowMap.autoUpdate = false; // avoid re-computing shadows
  130. renderer.render( scene, virtualCamera, renderTarget, true );
  131. renderer.vr.enabled = currentVrEnabled;
  132. renderer.shadowMap.autoUpdate = currentShadowAutoUpdate;
  133. renderer.setRenderTarget( currentRenderTarget );
  134. // restore viewport
  135. var bounds = camera.bounds;
  136. if ( bounds !== undefined ) {
  137. var size = renderer.getSize();
  138. var pixelRatio = renderer.getPixelRatio();
  139. viewport.x = bounds.x * size.width * pixelRatio;
  140. viewport.y = bounds.y * size.height * pixelRatio;
  141. viewport.z = bounds.z * size.width * pixelRatio;
  142. viewport.w = bounds.w * size.height * pixelRatio;
  143. renderer.state.viewport( viewport );
  144. }
  145. scope.visible = true;
  146. };
  147. } )();
  148. //
  149. this.onBeforeRender = function ( renderer, scene, camera ) {
  150. // ensure refractors are rendered only once per frame
  151. if ( camera.userData.refractor === true ) return;
  152. // avoid rendering when the refractor is viewed from behind
  153. if ( ! visible( camera ) === true ) return;
  154. // update
  155. updateRefractorPlane( camera );
  156. updateTextureMatrix( camera );
  157. updateVirtualCamera( camera );
  158. render( renderer, scene, camera );
  159. };
  160. };
  161. THREE.Refractor.prototype = Object.create( THREE.Mesh.prototype );
  162. THREE.Refractor.prototype.constructor = THREE.Refractor;
  163. THREE.DefaultRefractionShader = {
  164. uniforms: {
  165. 'color': {
  166. type: 'c',
  167. value: null
  168. },
  169. 'tDiffuse': {
  170. type: 't',
  171. value: null
  172. },
  173. 'textureMatrix': {
  174. type: 'm4',
  175. value: null
  176. }
  177. },
  178. vertexShader: [
  179. 'uniform mat4 textureMatrix;',
  180. 'varying vec4 vUv;',
  181. 'void main() {',
  182. ' vUv = textureMatrix * vec4( position, 1.0 );',
  183. ' gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );',
  184. '}'
  185. ].join( '\n' ),
  186. fragmentShader: [
  187. 'uniform vec3 color;',
  188. 'uniform sampler2D tDiffuse;',
  189. 'varying vec4 vUv;',
  190. 'float blendOverlay( float base, float blend ) {',
  191. ' return( base < 0.5 ? ( 2.0 * base * blend ) : ( 1.0 - 2.0 * ( 1.0 - base ) * ( 1.0 - blend ) ) );',
  192. '}',
  193. 'vec3 blendOverlay( vec3 base, vec3 blend ) {',
  194. ' return vec3( blendOverlay( base.r, blend.r ), blendOverlay( base.g, blend.g ),blendOverlay( base.b, blend.b ) );',
  195. '}',
  196. 'void main() {',
  197. ' vec4 base = texture2DProj( tDiffuse, vUv );',
  198. ' gl_FragColor = vec4( blendOverlay( base.rgb, color ), 1.0 );',
  199. '}'
  200. ].join( '\n' )
  201. };