Refractor.js 7.9 KB

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