Refractor.js 8.0 KB

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