Refractor.js 8.2 KB

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