ReflectorForSSRPass.js 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384
  1. import {
  2. Color,
  3. LinearFilter,
  4. MathUtils,
  5. Matrix4,
  6. Mesh,
  7. PerspectiveCamera,
  8. Plane,
  9. RGBFormat,
  10. ShaderMaterial,
  11. UniformsUtils,
  12. Vector2,
  13. Vector3,
  14. Vector4,
  15. WebGLRenderTarget,
  16. DepthTexture,
  17. UnsignedShortType,
  18. NearestFilter
  19. } from '../../../build/three.module.js';
  20. var ReflectorForSSRPass = function ( geometry, options ) {
  21. Mesh.call( this, geometry );
  22. this.type = 'ReflectorForSSRPass';
  23. var scope = this;
  24. options = options || {};
  25. var color = ( options.color !== undefined ) ? new Color( options.color ) : new Color( 0x7F7F7F );
  26. var textureWidth = options.textureWidth || 512;
  27. var textureHeight = options.textureHeight || 512;
  28. var clipBias = options.clipBias || 0;
  29. var shader = options.shader || ReflectorForSSRPass.ReflectorShader;
  30. var useDepthTexture = options.useDepthTexture === true;
  31. var yAxis = new Vector3( 0, 1, 0 );
  32. var vecTemp0 = new Vector3();
  33. var vecTemp1 = new Vector3();
  34. //
  35. scope.needsUpdate = false;
  36. scope.maxDistance = ReflectorForSSRPass.ReflectorShader.uniforms.maxDistance.value;
  37. scope.opacity = ReflectorForSSRPass.ReflectorShader.uniforms.opacity.value;
  38. scope.color = color;
  39. scope.worldYBias = options.worldYBias || 0;
  40. scope.resolution = options.resolution || new Vector2( window.innerWidth, window.innerHeight );
  41. scope._distanceAttenuation = ReflectorForSSRPass.ReflectorShader.defines.DISTANCE_ATTENUATION;
  42. Object.defineProperty( scope, 'distanceAttenuation', {
  43. get() {
  44. return scope._distanceAttenuation;
  45. },
  46. set( val ) {
  47. if ( scope._distanceAttenuation === val ) return;
  48. scope._distanceAttenuation = val;
  49. scope.material.defines.DISTANCE_ATTENUATION = val;
  50. scope.material.needsUpdate = true;
  51. }
  52. } );
  53. scope._fresnel = ReflectorForSSRPass.ReflectorShader.defines.FRESNEL;
  54. Object.defineProperty( scope, 'fresnel', {
  55. get() {
  56. return scope._fresnel;
  57. },
  58. set( val ) {
  59. if ( scope._fresnel === val ) return;
  60. scope._fresnel = val;
  61. scope.material.defines.FRESNEL = val;
  62. scope.material.needsUpdate = true;
  63. }
  64. } );
  65. var reflectorPlane = new Plane();
  66. var normal = new Vector3();
  67. var reflectorWorldPosition = new Vector3();
  68. var cameraWorldPosition = new Vector3();
  69. var rotationMatrix = new Matrix4();
  70. var lookAtPosition = new Vector3( 0, 0, - 1 );
  71. var clipPlane = new Vector4();
  72. var view = new Vector3();
  73. var target = new Vector3();
  74. var q = new Vector4();
  75. var textureMatrix = new Matrix4();
  76. var virtualCamera = new PerspectiveCamera();
  77. if ( useDepthTexture ) {
  78. var depthTexture = new DepthTexture();
  79. depthTexture.type = UnsignedShortType;
  80. depthTexture.minFilter = NearestFilter;
  81. depthTexture.magFilter = NearestFilter;
  82. }
  83. var parameters = {
  84. minFilter: LinearFilter,
  85. magFilter: LinearFilter,
  86. format: RGBFormat,
  87. depthTexture: useDepthTexture ? depthTexture : null,
  88. };
  89. var renderTarget = new WebGLRenderTarget( textureWidth, textureHeight, parameters );
  90. if ( ! MathUtils.isPowerOfTwo( textureWidth ) || ! MathUtils.isPowerOfTwo( textureHeight ) ) {
  91. renderTarget.texture.generateMipmaps = false;
  92. }
  93. var material = new ShaderMaterial( {
  94. transparent: useDepthTexture,
  95. defines: Object.assign( {}, ReflectorForSSRPass.ReflectorShader.defines, {
  96. useDepthTexture
  97. } ),
  98. uniforms: UniformsUtils.clone( shader.uniforms ),
  99. fragmentShader: shader.fragmentShader,
  100. vertexShader: shader.vertexShader
  101. } );
  102. material.uniforms[ 'tDiffuse' ].value = renderTarget.texture;
  103. material.uniforms[ 'color' ].value = scope.color;
  104. material.uniforms[ 'textureMatrix' ].value = textureMatrix;
  105. if ( useDepthTexture ) {
  106. material.uniforms[ 'tDepth' ].value = renderTarget.depthTexture;
  107. }
  108. this.material = material;
  109. this.doRender = function ( renderer, scene, camera ) {
  110. material.uniforms[ 'maxDistance' ].value = scope.maxDistance;
  111. material.uniforms[ 'color' ].value = scope.color;
  112. material.uniforms[ 'opacity' ].value = scope.opacity;
  113. material.uniforms[ 'worldYBias' ].value = scope.worldYBias;
  114. vecTemp0.copy( camera.position ).normalize();
  115. vecTemp1.copy( vecTemp0 ).reflect( yAxis );
  116. material.uniforms[ 'fresnelCoe' ].value = ( vecTemp0.dot( vecTemp1 ) + 1. ) / 2.; // TODO: Also need to use glsl viewPosition and viewNormal per pixel.
  117. reflectorWorldPosition.setFromMatrixPosition( scope.matrixWorld );
  118. cameraWorldPosition.setFromMatrixPosition( camera.matrixWorld );
  119. rotationMatrix.extractRotation( scope.matrixWorld );
  120. normal.set( 0, 0, 1 );
  121. normal.applyMatrix4( rotationMatrix );
  122. view.subVectors( reflectorWorldPosition, cameraWorldPosition );
  123. // Avoid rendering when reflector is facing away
  124. if ( view.dot( normal ) > 0 ) return;
  125. view.reflect( normal ).negate();
  126. view.add( reflectorWorldPosition );
  127. rotationMatrix.extractRotation( camera.matrixWorld );
  128. lookAtPosition.set( 0, 0, - 1 );
  129. lookAtPosition.applyMatrix4( rotationMatrix );
  130. lookAtPosition.add( cameraWorldPosition );
  131. target.subVectors( reflectorWorldPosition, lookAtPosition );
  132. target.reflect( normal ).negate();
  133. target.add( reflectorWorldPosition );
  134. virtualCamera.position.copy( view );
  135. virtualCamera.up.set( 0, 1, 0 );
  136. virtualCamera.up.applyMatrix4( rotationMatrix );
  137. virtualCamera.up.reflect( normal );
  138. virtualCamera.lookAt( target );
  139. virtualCamera.far = camera.far; // Used in WebGLBackground
  140. virtualCamera.updateMatrixWorld();
  141. virtualCamera.projectionMatrix.copy( camera.projectionMatrix );
  142. material.uniforms[ 'virtualCameraNear' ].value = virtualCamera.near;
  143. material.uniforms[ 'virtualCameraFar' ].value = virtualCamera.far;
  144. material.uniforms[ 'virtualCameraMatrixWorld' ].value= virtualCamera.matrixWorld;
  145. material.uniforms[ 'virtualCameraProjectionMatrix' ].value= virtualCamera.projectionMatrix;
  146. material.uniforms[ 'virtualCameraInverseProjectionMatrix' ].value= virtualCamera.projectionMatrixInverse;
  147. material.uniforms[ 'resolution' ].value = scope.resolution;
  148. // Update the texture matrix
  149. textureMatrix.set(
  150. 0.5, 0.0, 0.0, 0.5,
  151. 0.0, 0.5, 0.0, 0.5,
  152. 0.0, 0.0, 0.5, 0.5,
  153. 0.0, 0.0, 0.0, 1.0
  154. );
  155. textureMatrix.multiply( virtualCamera.projectionMatrix );
  156. textureMatrix.multiply( virtualCamera.matrixWorldInverse );
  157. textureMatrix.multiply( scope.matrixWorld );
  158. /* Note: For the sake of accurate tDepth, temporarily turned off this Oblique Near-Plane Clipping feature. https://github.com/mrdoob/three.js/pull/21403
  159. // Now update projection matrix with new clip plane, implementing code from: http://www.terathon.com/code/oblique.html
  160. // Paper explaining this technique: http://www.terathon.com/lengyel/Lengyel-Oblique.pdf
  161. reflectorPlane.setFromNormalAndCoplanarPoint( normal, reflectorWorldPosition );
  162. reflectorPlane.applyMatrix4( virtualCamera.matrixWorldInverse );
  163. clipPlane.set( reflectorPlane.normal.x, reflectorPlane.normal.y, reflectorPlane.normal.z, reflectorPlane.constant );
  164. var projectionMatrix = virtualCamera.projectionMatrix;
  165. q.x = ( Math.sign( clipPlane.x ) + projectionMatrix.elements[ 8 ] ) / projectionMatrix.elements[ 0 ];
  166. q.y = ( Math.sign( clipPlane.y ) + projectionMatrix.elements[ 9 ] ) / projectionMatrix.elements[ 5 ];
  167. q.z = - 1.0;
  168. q.w = ( 1.0 + projectionMatrix.elements[ 10 ] ) / projectionMatrix.elements[ 14 ];
  169. // Calculate the scaled plane vector
  170. clipPlane.multiplyScalar( 2.0 / clipPlane.dot( q ) );
  171. // Replacing the third row of the projection matrix
  172. projectionMatrix.elements[ 2 ] = clipPlane.x;
  173. projectionMatrix.elements[ 6 ] = clipPlane.y;
  174. projectionMatrix.elements[ 10 ] = clipPlane.z + 1.0 - clipBias;
  175. projectionMatrix.elements[ 14 ] = clipPlane.w;
  176. */
  177. // Render
  178. renderTarget.texture.encoding = renderer.outputEncoding;
  179. // scope.visible = false;
  180. var currentRenderTarget = renderer.getRenderTarget();
  181. var currentXrEnabled = renderer.xr.enabled;
  182. var currentShadowAutoUpdate = renderer.shadowMap.autoUpdate;
  183. renderer.xr.enabled = false; // Avoid camera modification
  184. renderer.shadowMap.autoUpdate = false; // Avoid re-computing shadows
  185. renderer.setRenderTarget( renderTarget );
  186. renderer.state.buffers.depth.setMask( true ); // make sure the depth buffer is writable so it can be properly cleared, see #18897
  187. if ( renderer.autoClear === false ) renderer.clear();
  188. renderer.render( scene, virtualCamera );
  189. renderer.xr.enabled = currentXrEnabled;
  190. renderer.shadowMap.autoUpdate = currentShadowAutoUpdate;
  191. renderer.setRenderTarget( currentRenderTarget );
  192. // Restore viewport
  193. var viewport = camera.viewport;
  194. if ( viewport !== undefined ) {
  195. renderer.state.viewport( viewport );
  196. }
  197. // scope.visible = true;
  198. };
  199. this.getRenderTarget = function () {
  200. return renderTarget;
  201. };
  202. };
  203. ReflectorForSSRPass.prototype = Object.create( Mesh.prototype );
  204. ReflectorForSSRPass.prototype.constructor = ReflectorForSSRPass;
  205. ReflectorForSSRPass.ReflectorShader = {
  206. defines: {
  207. DISTANCE_ATTENUATION: true,
  208. FRESNEL: true,
  209. },
  210. uniforms: {
  211. color: { value: null },
  212. tDiffuse: { value: null },
  213. tDepth: { value: null },
  214. textureMatrix: { value: new Matrix4() },
  215. maxDistance: { value: 180 },
  216. opacity: { value: 0.5 },
  217. fresnelCoe: { value: null },
  218. worldYBias: { value: null },
  219. virtualCameraNear: { value: null },
  220. virtualCameraFar: { value: null },
  221. virtualCameraProjectionMatrix: { value: new Matrix4() },
  222. virtualCameraMatrixWorld: { value: new Matrix4() },
  223. virtualCameraInverseProjectionMatrix: { value: new Matrix4() },
  224. resolution: { value: new Vector2() },
  225. },
  226. vertexShader: [
  227. 'uniform mat4 textureMatrix;',
  228. 'varying vec4 vUv;',
  229. 'void main() {',
  230. ' vUv = textureMatrix * vec4( position, 1.0 );',
  231. ' gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );',
  232. '}'
  233. ].join( '\n' ),
  234. fragmentShader: `
  235. uniform vec3 color;
  236. uniform sampler2D tDiffuse;
  237. uniform sampler2D tDepth;
  238. uniform float maxDistance;
  239. uniform float opacity;
  240. uniform float fresnelCoe;
  241. uniform float worldYBias;
  242. uniform float virtualCameraNear;
  243. uniform float virtualCameraFar;
  244. uniform mat4 virtualCameraProjectionMatrix;
  245. uniform mat4 virtualCameraInverseProjectionMatrix;
  246. uniform mat4 virtualCameraMatrixWorld;
  247. uniform vec2 resolution;
  248. varying vec4 vUv;
  249. #include <packing>
  250. float blendOverlay( float base, float blend ) {
  251. return( base < 0.5 ? ( 2.0 * base * blend ) : ( 1.0 - 2.0 * ( 1.0 - base ) * ( 1.0 - blend ) ) );
  252. }
  253. vec3 blendOverlay( vec3 base, vec3 blend ) {
  254. return vec3( blendOverlay( base.r, blend.r ), blendOverlay( base.g, blend.g ), blendOverlay( base.b, blend.b ) );
  255. }
  256. float getDepth( const in vec2 uv ) {
  257. return texture2D( tDepth, uv ).x;
  258. }
  259. float getViewZ( const in float depth ) {
  260. return perspectiveDepthToViewZ( depth, virtualCameraNear, virtualCameraFar );
  261. }
  262. vec3 getViewPosition( const in vec2 uv, const in float depth/*clip space*/, const in float clipW ) {
  263. vec4 clipPosition = vec4( ( vec3( uv, depth ) - 0.5 ) * 2.0, 1.0 );//ndc
  264. clipPosition *= clipW; //clip
  265. return ( virtualCameraInverseProjectionMatrix * clipPosition ).xyz;//view
  266. }
  267. void main() {
  268. vec4 base = texture2DProj( tDiffuse, vUv );
  269. #ifdef useDepthTexture
  270. vec2 uv=(gl_FragCoord.xy-.5)/resolution.xy;
  271. uv.x=1.-uv.x;
  272. float depth = texture2DProj( tDepth, vUv ).r;
  273. float viewZ = getViewZ( depth );
  274. float clipW = virtualCameraProjectionMatrix[2][3] * viewZ+virtualCameraProjectionMatrix[3][3];
  275. vec3 viewPosition=getViewPosition( uv, depth, clipW );
  276. vec3 worldPosition=(virtualCameraMatrixWorld*vec4(viewPosition,1)).xyz;
  277. worldPosition.y+=worldYBias; // TODO: Don't know why not start from zero, temporarily use manually defined bias, need fix afterwards.
  278. worldPosition.y=max(0.,worldPosition.y);
  279. if(worldPosition.y>maxDistance) discard;
  280. float op=opacity;
  281. #ifdef DISTANCE_ATTENUATION
  282. float ratio=1.-(worldPosition.y/maxDistance);
  283. float attenuation=ratio*ratio;
  284. op=opacity*attenuation;
  285. #endif
  286. #ifdef FRESNEL
  287. op*=fresnelCoe;
  288. #endif
  289. gl_FragColor = vec4( blendOverlay( base.rgb, color ), op );
  290. #else
  291. gl_FragColor = vec4( blendOverlay( base.rgb, color ), 1.0 );
  292. #endif
  293. }
  294. `,
  295. };
  296. export { ReflectorForSSRPass };