Refractor.js 8.3 KB

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