ReflectorForSSRPass.js 11 KB

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