Refractor.js 7.9 KB

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