Refractor.js 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322
  1. import {
  2. Color,
  3. Matrix4,
  4. Mesh,
  5. PerspectiveCamera,
  6. Plane,
  7. Quaternion,
  8. ShaderMaterial,
  9. UniformsUtils,
  10. Vector3,
  11. Vector4,
  12. WebGLRenderTarget
  13. } from 'three';
  14. class Refractor extends Mesh {
  15. constructor( geometry, options = {} ) {
  16. super( geometry );
  17. this.type = 'Refractor';
  18. const scope = this;
  19. const color = ( options.color !== undefined ) ? new Color( options.color ) : new Color( 0x7F7F7F );
  20. const textureWidth = options.textureWidth || 512;
  21. const textureHeight = options.textureHeight || 512;
  22. const clipBias = options.clipBias || 0;
  23. const shader = options.shader || Refractor.RefractorShader;
  24. //
  25. const virtualCamera = new PerspectiveCamera();
  26. virtualCamera.matrixAutoUpdate = false;
  27. virtualCamera.userData.refractor = true;
  28. //
  29. const refractorPlane = new Plane();
  30. const textureMatrix = new Matrix4();
  31. // render target
  32. const renderTarget = new WebGLRenderTarget( textureWidth, textureHeight );
  33. // material
  34. this.material = new ShaderMaterial( {
  35. uniforms: 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. const visible = ( function () {
  45. const refractorWorldPosition = new Vector3();
  46. const cameraWorldPosition = new Vector3();
  47. const rotationMatrix = new Matrix4();
  48. const view = new Vector3();
  49. const normal = new 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. const updateRefractorPlane = ( function () {
  61. const normal = new Vector3();
  62. const position = new Vector3();
  63. const quaternion = new Quaternion();
  64. const scale = new 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. const updateVirtualCamera = ( function () {
  74. const clipPlane = new Plane();
  75. const clipVector = new Vector4();
  76. const q = new Vector4();
  77. return function updateVirtualCamera( camera ) {
  78. virtualCamera.matrixWorld.copy( camera.matrixWorld );
  79. virtualCamera.matrixWorldInverse.copy( virtualCamera.matrixWorld ).invert();
  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. const 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. function render( renderer, scene, camera ) {
  123. scope.visible = false;
  124. const currentRenderTarget = renderer.getRenderTarget();
  125. const currentXrEnabled = renderer.xr.enabled;
  126. const currentShadowAutoUpdate = renderer.shadowMap.autoUpdate;
  127. renderer.xr.enabled = false; // avoid camera modification
  128. renderer.shadowMap.autoUpdate = false; // avoid re-computing shadows
  129. renderer.setRenderTarget( renderTarget );
  130. if ( renderer.autoClear === false ) renderer.clear();
  131. renderer.render( scene, virtualCamera );
  132. renderer.xr.enabled = currentXrEnabled;
  133. renderer.shadowMap.autoUpdate = currentShadowAutoUpdate;
  134. renderer.setRenderTarget( currentRenderTarget );
  135. // restore viewport
  136. const viewport = camera.viewport;
  137. if ( viewport !== undefined ) {
  138. renderer.state.viewport( viewport );
  139. }
  140. scope.visible = true;
  141. }
  142. //
  143. this.onBeforeRender = function ( renderer, scene, camera ) {
  144. // Render
  145. renderTarget.texture.encoding = renderer.outputEncoding;
  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. this.dispose = function () {
  160. renderTarget.dispose();
  161. scope.material.dispose();
  162. };
  163. }
  164. }
  165. Refractor.prototype.isRefractor = true;
  166. Refractor.RefractorShader = {
  167. uniforms: {
  168. 'color': {
  169. value: null
  170. },
  171. 'tDiffuse': {
  172. value: null
  173. },
  174. 'textureMatrix': {
  175. value: null
  176. }
  177. },
  178. vertexShader: /* glsl */`
  179. uniform mat4 textureMatrix;
  180. varying vec4 vUv;
  181. void main() {
  182. vUv = textureMatrix * vec4( position, 1.0 );
  183. gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );
  184. }`,
  185. fragmentShader: /* glsl */`
  186. uniform vec3 color;
  187. uniform sampler2D tDiffuse;
  188. varying vec4 vUv;
  189. float blendOverlay( float base, float blend ) {
  190. return( base < 0.5 ? ( 2.0 * base * blend ) : ( 1.0 - 2.0 * ( 1.0 - base ) * ( 1.0 - blend ) ) );
  191. }
  192. vec3 blendOverlay( vec3 base, vec3 blend ) {
  193. return vec3( blendOverlay( base.r, blend.r ), blendOverlay( base.g, blend.g ), blendOverlay( base.b, blend.b ) );
  194. }
  195. void main() {
  196. vec4 base = texture2DProj( tDiffuse, vUv );
  197. gl_FragColor = vec4( blendOverlay( base.rgb, color ), 1.0 );
  198. }`
  199. };
  200. export { Refractor };