Refractor.js 7.9 KB

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