Refractor.js 8.0 KB

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