Refractor.js 8.3 KB

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