Refractor.js 7.9 KB

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