ReflectorForSSRPass.js 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391
  1. import {
  2. Color,
  3. Matrix4,
  4. Mesh,
  5. PerspectiveCamera,
  6. ShaderMaterial,
  7. UniformsUtils,
  8. Vector2,
  9. Vector3,
  10. WebGLRenderTarget,
  11. DepthTexture,
  12. UnsignedShortType,
  13. NearestFilter,
  14. Plane,
  15. HalfFloatType
  16. } from 'three';
  17. /**
  18. * A special version of {@link Reflector} for usage with {@link SSRPass}.
  19. *
  20. * @augments Mesh
  21. */
  22. class ReflectorForSSRPass extends Mesh {
  23. /**
  24. * Constructs a new reflector.
  25. *
  26. * @param {BufferGeometry} geometry - The reflector's geometry.
  27. * @param {ReflectorForSSRPass~Options} [options] - The configuration options.
  28. */
  29. constructor( geometry, options = {} ) {
  30. super( geometry );
  31. this.isReflectorForSSRPass = true;
  32. this.type = 'ReflectorForSSRPass';
  33. const scope = this;
  34. const color = ( options.color !== undefined ) ? new Color( options.color ) : new Color( 0x7F7F7F );
  35. const textureWidth = options.textureWidth || 512;
  36. const textureHeight = options.textureHeight || 512;
  37. const clipBias = options.clipBias || 0;
  38. const shader = options.shader || ReflectorForSSRPass.ReflectorShader;
  39. const useDepthTexture = options.useDepthTexture === true;
  40. const yAxis = new Vector3( 0, 1, 0 );
  41. const vecTemp0 = new Vector3();
  42. const vecTemp1 = new Vector3();
  43. //
  44. scope.needsUpdate = false;
  45. scope.maxDistance = ReflectorForSSRPass.ReflectorShader.uniforms.maxDistance.value;
  46. scope.opacity = ReflectorForSSRPass.ReflectorShader.uniforms.opacity.value;
  47. scope.color = color;
  48. scope.resolution = options.resolution || new Vector2( window.innerWidth, window.innerHeight );
  49. scope._distanceAttenuation = ReflectorForSSRPass.ReflectorShader.defines.DISTANCE_ATTENUATION;
  50. Object.defineProperty( scope, 'distanceAttenuation', {
  51. get() {
  52. return scope._distanceAttenuation;
  53. },
  54. set( val ) {
  55. if ( scope._distanceAttenuation === val ) return;
  56. scope._distanceAttenuation = val;
  57. scope.material.defines.DISTANCE_ATTENUATION = val;
  58. scope.material.needsUpdate = true;
  59. }
  60. } );
  61. scope._fresnel = ReflectorForSSRPass.ReflectorShader.defines.FRESNEL;
  62. Object.defineProperty( scope, 'fresnel', {
  63. get() {
  64. return scope._fresnel;
  65. },
  66. set( val ) {
  67. if ( scope._fresnel === val ) return;
  68. scope._fresnel = val;
  69. scope.material.defines.FRESNEL = val;
  70. scope.material.needsUpdate = true;
  71. }
  72. } );
  73. const normal = new Vector3();
  74. const reflectorWorldPosition = new Vector3();
  75. const cameraWorldPosition = new Vector3();
  76. const rotationMatrix = new Matrix4();
  77. const lookAtPosition = new Vector3( 0, 0, - 1 );
  78. const view = new Vector3();
  79. const target = new Vector3();
  80. const textureMatrix = new Matrix4();
  81. const virtualCamera = new PerspectiveCamera();
  82. let depthTexture;
  83. if ( useDepthTexture ) {
  84. depthTexture = new DepthTexture();
  85. depthTexture.type = UnsignedShortType;
  86. depthTexture.minFilter = NearestFilter;
  87. depthTexture.magFilter = NearestFilter;
  88. }
  89. const parameters = {
  90. depthTexture: useDepthTexture ? depthTexture : null,
  91. type: HalfFloatType
  92. };
  93. const renderTarget = new WebGLRenderTarget( textureWidth, textureHeight, parameters );
  94. const material = new ShaderMaterial( {
  95. name: ( shader.name !== undefined ) ? shader.name : 'unspecified',
  96. transparent: useDepthTexture,
  97. defines: Object.assign( {}, ReflectorForSSRPass.ReflectorShader.defines, {
  98. useDepthTexture
  99. } ),
  100. uniforms: UniformsUtils.clone( shader.uniforms ),
  101. fragmentShader: shader.fragmentShader,
  102. vertexShader: shader.vertexShader
  103. } );
  104. material.uniforms[ 'tDiffuse' ].value = renderTarget.texture;
  105. material.uniforms[ 'color' ].value = scope.color;
  106. material.uniforms[ 'textureMatrix' ].value = textureMatrix;
  107. if ( useDepthTexture ) {
  108. material.uniforms[ 'tDepth' ].value = renderTarget.depthTexture;
  109. }
  110. this.material = material;
  111. const globalPlane = new Plane( new Vector3( 0, 1, 0 ), clipBias );
  112. const globalPlanes = [ globalPlane ];
  113. this.doRender = function ( renderer, scene, camera ) {
  114. material.uniforms[ 'maxDistance' ].value = scope.maxDistance;
  115. material.uniforms[ 'color' ].value = scope.color;
  116. material.uniforms[ 'opacity' ].value = scope.opacity;
  117. vecTemp0.copy( camera.position ).normalize();
  118. vecTemp1.copy( vecTemp0 ).reflect( yAxis );
  119. material.uniforms[ 'fresnelCoe' ].value = ( vecTemp0.dot( vecTemp1 ) + 1. ) / 2.; // TODO: Also need to use glsl viewPosition and viewNormal per pixel.
  120. reflectorWorldPosition.setFromMatrixPosition( scope.matrixWorld );
  121. cameraWorldPosition.setFromMatrixPosition( camera.matrixWorld );
  122. rotationMatrix.extractRotation( scope.matrixWorld );
  123. normal.set( 0, 0, 1 );
  124. normal.applyMatrix4( rotationMatrix );
  125. view.subVectors( reflectorWorldPosition, cameraWorldPosition );
  126. // Avoid rendering when reflector is facing away
  127. if ( view.dot( normal ) > 0 ) return;
  128. view.reflect( normal ).negate();
  129. view.add( reflectorWorldPosition );
  130. rotationMatrix.extractRotation( camera.matrixWorld );
  131. lookAtPosition.set( 0, 0, - 1 );
  132. lookAtPosition.applyMatrix4( rotationMatrix );
  133. lookAtPosition.add( cameraWorldPosition );
  134. target.subVectors( reflectorWorldPosition, lookAtPosition );
  135. target.reflect( normal ).negate();
  136. target.add( reflectorWorldPosition );
  137. virtualCamera.position.copy( view );
  138. virtualCamera.up.set( 0, 1, 0 );
  139. virtualCamera.up.applyMatrix4( rotationMatrix );
  140. virtualCamera.up.reflect( normal );
  141. virtualCamera.lookAt( target );
  142. virtualCamera.far = camera.far; // Used in WebGLBackground
  143. virtualCamera.updateMatrixWorld();
  144. virtualCamera.projectionMatrix.copy( camera.projectionMatrix );
  145. material.uniforms[ 'virtualCameraNear' ].value = camera.near;
  146. material.uniforms[ 'virtualCameraFar' ].value = camera.far;
  147. material.uniforms[ 'virtualCameraMatrixWorld' ].value = virtualCamera.matrixWorld;
  148. material.uniforms[ 'virtualCameraProjectionMatrix' ].value = camera.projectionMatrix;
  149. material.uniforms[ 'virtualCameraProjectionMatrixInverse' ].value = camera.projectionMatrixInverse;
  150. material.uniforms[ 'resolution' ].value = scope.resolution;
  151. // Update the texture matrix
  152. textureMatrix.set(
  153. 0.5, 0.0, 0.0, 0.5,
  154. 0.0, 0.5, 0.0, 0.5,
  155. 0.0, 0.0, 0.5, 0.5,
  156. 0.0, 0.0, 0.0, 1.0
  157. );
  158. textureMatrix.multiply( virtualCamera.projectionMatrix );
  159. textureMatrix.multiply( virtualCamera.matrixWorldInverse );
  160. textureMatrix.multiply( scope.matrixWorld );
  161. // scope.visible = false;
  162. const currentRenderTarget = renderer.getRenderTarget();
  163. const currentXrEnabled = renderer.xr.enabled;
  164. const currentShadowAutoUpdate = renderer.shadowMap.autoUpdate;
  165. const currentClippingPlanes = renderer.clippingPlanes;
  166. renderer.xr.enabled = false; // Avoid camera modification
  167. renderer.shadowMap.autoUpdate = false; // Avoid re-computing shadows
  168. renderer.clippingPlanes = globalPlanes;
  169. renderer.setRenderTarget( renderTarget );
  170. renderer.state.buffers.depth.setMask( true ); // make sure the depth buffer is writable so it can be properly cleared, see #18897
  171. if ( renderer.autoClear === false ) renderer.clear();
  172. renderer.render( scene, virtualCamera );
  173. renderer.xr.enabled = currentXrEnabled;
  174. renderer.shadowMap.autoUpdate = currentShadowAutoUpdate;
  175. renderer.clippingPlanes = currentClippingPlanes;
  176. renderer.setRenderTarget( currentRenderTarget );
  177. // Restore viewport
  178. const viewport = camera.viewport;
  179. if ( viewport !== undefined ) {
  180. renderer.state.viewport( viewport );
  181. }
  182. // scope.visible = true;
  183. };
  184. /**
  185. * Returns the reflector's internal render target.
  186. *
  187. * @return {WebGLRenderTarget} The internal render target
  188. */
  189. this.getRenderTarget = function () {
  190. return renderTarget;
  191. };
  192. /**
  193. * Frees the GPU-related resources allocated by this instance. Call this
  194. * method whenever this instance is no longer used in your app.
  195. */
  196. this.dispose = function () {
  197. renderTarget.dispose();
  198. scope.material.dispose();
  199. };
  200. }
  201. }
  202. ReflectorForSSRPass.ReflectorShader = {
  203. name: '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: /* glsl */`
  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. fragmentShader: /* glsl */`
  231. uniform vec3 color;
  232. uniform sampler2D tDiffuse;
  233. uniform sampler2D tDepth;
  234. uniform float maxDistance;
  235. uniform float opacity;
  236. uniform float fresnelCoe;
  237. uniform float virtualCameraNear;
  238. uniform float virtualCameraFar;
  239. uniform mat4 virtualCameraProjectionMatrix;
  240. uniform mat4 virtualCameraProjectionMatrixInverse;
  241. uniform mat4 virtualCameraMatrixWorld;
  242. uniform vec2 resolution;
  243. varying vec4 vUv;
  244. #include <packing>
  245. float blendOverlay( float base, float blend ) {
  246. return( base < 0.5 ? ( 2.0 * base * blend ) : ( 1.0 - 2.0 * ( 1.0 - base ) * ( 1.0 - blend ) ) );
  247. }
  248. vec3 blendOverlay( vec3 base, vec3 blend ) {
  249. return vec3( blendOverlay( base.r, blend.r ), blendOverlay( base.g, blend.g ), blendOverlay( base.b, blend.b ) );
  250. }
  251. float getDepth( const in vec2 uv ) {
  252. return texture2D( tDepth, uv ).x;
  253. }
  254. float getViewZ( const in float depth ) {
  255. return perspectiveDepthToViewZ( depth, virtualCameraNear, virtualCameraFar );
  256. }
  257. vec3 getViewPosition( const in vec2 uv, const in float depth/*clip space*/, const in float clipW ) {
  258. vec4 clipPosition = vec4( ( vec3( uv, depth ) - 0.5 ) * 2.0, 1.0 );//ndc
  259. clipPosition *= clipW; //clip
  260. return ( virtualCameraProjectionMatrixInverse * clipPosition ).xyz;//view
  261. }
  262. void main() {
  263. vec4 base = texture2DProj( tDiffuse, vUv );
  264. #ifdef useDepthTexture
  265. vec2 uv=(gl_FragCoord.xy-.5)/resolution.xy;
  266. uv.x=1.-uv.x;
  267. float depth = texture2DProj( tDepth, vUv ).r;
  268. float viewZ = getViewZ( depth );
  269. float clipW = virtualCameraProjectionMatrix[2][3] * viewZ+virtualCameraProjectionMatrix[3][3];
  270. vec3 viewPosition=getViewPosition( uv, depth, clipW );
  271. vec3 worldPosition=(virtualCameraMatrixWorld*vec4(viewPosition,1)).xyz;
  272. if(worldPosition.y>maxDistance) discard;
  273. float op=opacity;
  274. #ifdef DISTANCE_ATTENUATION
  275. float ratio=1.-(worldPosition.y/maxDistance);
  276. float attenuation=ratio*ratio;
  277. op=opacity*attenuation;
  278. #endif
  279. #ifdef FRESNEL
  280. op*=fresnelCoe;
  281. #endif
  282. gl_FragColor = vec4( blendOverlay( base.rgb, color ), op );
  283. #else
  284. gl_FragColor = vec4( blendOverlay( base.rgb, color ), 1.0 );
  285. #endif
  286. }
  287. `,
  288. };
  289. /**
  290. * Constructor options of `ReflectorForSSRPass`.
  291. *
  292. * @typedef {Object} ReflectorForSSRPass~Options
  293. * @property {number|Color|string} [color=0x7F7F7F] - The reflector's color.
  294. * @property {number} [textureWidth=512] - The texture width. A higher value results in more clear reflections but is also more expensive.
  295. * @property {number} [textureHeight=512] - The texture height. A higher value results in more clear reflections but is also more expensive.
  296. * @property {number} [clipBias=0] - The clip bias.
  297. * @property {Object} [shader] - Can be used to pass in a custom shader that defines how the reflective view is projected onto the reflector's geometry.
  298. * @property {boolean} [useDepthTexture=true] - Whether to store depth values in a texture or not.
  299. **/
  300. export { ReflectorForSSRPass };
粤ICP备19079148号