ReflectorForSSRPass.js 11 KB

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