Reflector.js 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337
  1. import {
  2. Color,
  3. Matrix4,
  4. Mesh,
  5. PerspectiveCamera,
  6. Plane,
  7. ShaderMaterial,
  8. UniformsUtils,
  9. Vector3,
  10. Vector4,
  11. WebGLRenderTarget,
  12. HalfFloatType
  13. } from 'three';
  14. /**
  15. * Can be used to create a flat, reflective surface like a mirror.
  16. *
  17. * Note that this class can only be used with {@link WebGLRenderer}.
  18. * When using {@link WebGPURenderer}, use {@link ReflectorNode}.
  19. *
  20. * ```js
  21. * const geometry = new THREE.PlaneGeometry( 100, 100 );
  22. *
  23. * const reflector = new Reflector( geometry, {
  24. * clipBias: 0.003,
  25. * textureWidth: window.innerWidth * window.devicePixelRatio,
  26. * textureHeight: window.innerHeight * window.devicePixelRatio,
  27. * color: 0xc1cbcb
  28. * } );
  29. *
  30. * scene.add( reflector );
  31. * ```
  32. *
  33. * @augments Mesh
  34. */
  35. class Reflector extends Mesh {
  36. /**
  37. * Constructs a new reflector.
  38. *
  39. * @param {BufferGeometry} geometry - The reflector's geometry.
  40. * @param {Reflector~Options} [options] - The configuration options.
  41. */
  42. constructor( geometry, options = {} ) {
  43. super( geometry );
  44. /**
  45. * This flag can be used for type testing.
  46. *
  47. * @type {boolean}
  48. * @readonly
  49. * @default true
  50. */
  51. this.isReflector = true;
  52. this.type = 'Reflector';
  53. /**
  54. * Whether to force an update, no matter if the reflector
  55. * is in view or not.
  56. *
  57. * @type {boolean}
  58. * @default false
  59. */
  60. this.forceUpdate = false;
  61. /**
  62. * The reflector's virtual camera. This is used to render
  63. * the scene from the mirror's point of view.
  64. *
  65. * @type {PerspectiveCamera}
  66. */
  67. this.camera = new PerspectiveCamera();
  68. const scope = this;
  69. const color = ( options.color !== undefined ) ? new Color( options.color ) : new Color( 0x7F7F7F );
  70. const textureWidth = options.textureWidth || 512;
  71. const textureHeight = options.textureHeight || 512;
  72. const clipBias = options.clipBias || 0;
  73. const shader = options.shader || Reflector.ReflectorShader;
  74. const multisample = ( options.multisample !== undefined ) ? options.multisample : 4;
  75. //
  76. const reflectorPlane = new Plane();
  77. const normal = new Vector3();
  78. const reflectorWorldPosition = new Vector3();
  79. const cameraWorldPosition = new Vector3();
  80. const rotationMatrix = new Matrix4();
  81. const lookAtPosition = new Vector3( 0, 0, - 1 );
  82. const clipPlane = new Vector4();
  83. const view = new Vector3();
  84. const target = new Vector3();
  85. const q = new Vector4();
  86. const textureMatrix = new Matrix4();
  87. const virtualCamera = this.camera;
  88. const renderTarget = new WebGLRenderTarget( textureWidth, textureHeight, { samples: multisample, type: HalfFloatType } );
  89. const material = new ShaderMaterial( {
  90. name: ( shader.name !== undefined ) ? shader.name : 'unspecified',
  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 = color;
  97. material.uniforms[ 'textureMatrix' ].value = textureMatrix;
  98. this.material = material;
  99. this.onBeforeRender = function ( renderer, scene, camera ) {
  100. reflectorWorldPosition.setFromMatrixPosition( scope.matrixWorld );
  101. cameraWorldPosition.setFromMatrixPosition( camera.matrixWorld );
  102. rotationMatrix.extractRotation( scope.matrixWorld );
  103. normal.set( 0, 0, 1 );
  104. normal.applyMatrix4( rotationMatrix );
  105. view.subVectors( reflectorWorldPosition, cameraWorldPosition );
  106. // Avoid rendering when reflector is facing away unless forcing an update
  107. const isFacingAway = view.dot( normal ) > 0;
  108. if ( isFacingAway === true && this.forceUpdate === false ) return;
  109. view.reflect( normal ).negate();
  110. view.add( reflectorWorldPosition );
  111. rotationMatrix.extractRotation( camera.matrixWorld );
  112. lookAtPosition.set( 0, 0, - 1 );
  113. lookAtPosition.applyMatrix4( rotationMatrix );
  114. lookAtPosition.add( cameraWorldPosition );
  115. target.subVectors( reflectorWorldPosition, lookAtPosition );
  116. target.reflect( normal ).negate();
  117. target.add( reflectorWorldPosition );
  118. virtualCamera.position.copy( view );
  119. virtualCamera.up.set( 0, 1, 0 );
  120. virtualCamera.up.applyMatrix4( rotationMatrix );
  121. virtualCamera.up.reflect( normal );
  122. virtualCamera.lookAt( target );
  123. virtualCamera.far = camera.far; // Used in WebGLBackground
  124. virtualCamera.updateMatrixWorld();
  125. virtualCamera.projectionMatrix.copy( camera.projectionMatrix );
  126. // Update the texture matrix
  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. textureMatrix.multiply( virtualCamera.projectionMatrix );
  134. textureMatrix.multiply( virtualCamera.matrixWorldInverse );
  135. textureMatrix.multiply( scope.matrixWorld );
  136. // Now update projection matrix with new clip plane, implementing code from: http://www.terathon.com/code/oblique.html
  137. // Paper explaining this technique: http://www.terathon.com/lengyel/Lengyel-Oblique.pdf
  138. reflectorPlane.setFromNormalAndCoplanarPoint( normal, reflectorWorldPosition );
  139. reflectorPlane.applyMatrix4( virtualCamera.matrixWorldInverse );
  140. clipPlane.set( reflectorPlane.normal.x, reflectorPlane.normal.y, reflectorPlane.normal.z, reflectorPlane.constant );
  141. const projectionMatrix = virtualCamera.projectionMatrix;
  142. q.x = ( Math.sign( clipPlane.x ) + projectionMatrix.elements[ 8 ] ) / projectionMatrix.elements[ 0 ];
  143. q.y = ( Math.sign( clipPlane.y ) + projectionMatrix.elements[ 9 ] ) / projectionMatrix.elements[ 5 ];
  144. q.z = - 1.0;
  145. q.w = ( 1.0 + projectionMatrix.elements[ 10 ] ) / projectionMatrix.elements[ 14 ];
  146. // Calculate the scaled plane vector
  147. clipPlane.multiplyScalar( 2.0 / clipPlane.dot( q ) );
  148. // Replacing the third row of the projection matrix
  149. projectionMatrix.elements[ 2 ] = clipPlane.x;
  150. projectionMatrix.elements[ 6 ] = clipPlane.y;
  151. projectionMatrix.elements[ 10 ] = clipPlane.z + 1.0 - clipBias;
  152. projectionMatrix.elements[ 14 ] = clipPlane.w;
  153. // Render
  154. scope.visible = false;
  155. const currentRenderTarget = renderer.getRenderTarget();
  156. const currentXrEnabled = renderer.xr.enabled;
  157. const currentShadowAutoUpdate = renderer.shadowMap.autoUpdate;
  158. renderer.xr.enabled = false; // Avoid camera modification
  159. renderer.shadowMap.autoUpdate = false; // Avoid re-computing shadows
  160. renderer.setRenderTarget( renderTarget );
  161. renderer.state.buffers.depth.setMask( true ); // make sure the depth buffer is writable so it can be properly cleared, see #18897
  162. if ( renderer.autoClear === false ) renderer.clear();
  163. renderer.render( scene, virtualCamera );
  164. renderer.xr.enabled = currentXrEnabled;
  165. renderer.shadowMap.autoUpdate = currentShadowAutoUpdate;
  166. renderer.setRenderTarget( currentRenderTarget );
  167. // Restore viewport
  168. const viewport = camera.viewport;
  169. if ( viewport !== undefined ) {
  170. renderer.state.viewport( viewport );
  171. }
  172. scope.visible = true;
  173. this.forceUpdate = false;
  174. };
  175. /**
  176. * Returns the reflector's internal render target.
  177. *
  178. * @return {WebGLRenderTarget} The internal render target
  179. */
  180. this.getRenderTarget = function () {
  181. return renderTarget;
  182. };
  183. /**
  184. * Frees the GPU-related resources allocated by this instance. Call this
  185. * method whenever this instance is no longer used in your app.
  186. */
  187. this.dispose = function () {
  188. renderTarget.dispose();
  189. scope.material.dispose();
  190. };
  191. }
  192. }
  193. Reflector.ReflectorShader = {
  194. name: 'ReflectorShader',
  195. uniforms: {
  196. 'color': {
  197. value: null
  198. },
  199. 'tDiffuse': {
  200. value: null
  201. },
  202. 'textureMatrix': {
  203. value: null
  204. }
  205. },
  206. vertexShader: /* glsl */`
  207. uniform mat4 textureMatrix;
  208. varying vec4 vUv;
  209. #include <common>
  210. #include <logdepthbuf_pars_vertex>
  211. void main() {
  212. vUv = textureMatrix * vec4( position, 1.0 );
  213. gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );
  214. #include <logdepthbuf_vertex>
  215. }`,
  216. fragmentShader: /* glsl */`
  217. uniform vec3 color;
  218. uniform sampler2D tDiffuse;
  219. varying vec4 vUv;
  220. #include <logdepthbuf_pars_fragment>
  221. float blendOverlay( float base, float blend ) {
  222. return( base < 0.5 ? ( 2.0 * base * blend ) : ( 1.0 - 2.0 * ( 1.0 - base ) * ( 1.0 - blend ) ) );
  223. }
  224. vec3 blendOverlay( vec3 base, vec3 blend ) {
  225. return vec3( blendOverlay( base.r, blend.r ), blendOverlay( base.g, blend.g ), blendOverlay( base.b, blend.b ) );
  226. }
  227. void main() {
  228. #include <logdepthbuf_fragment>
  229. vec4 base = texture2DProj( tDiffuse, vUv );
  230. gl_FragColor = vec4( blendOverlay( base.rgb, color ), 1.0 );
  231. #include <tonemapping_fragment>
  232. #include <colorspace_fragment>
  233. }`
  234. };
  235. /**
  236. * Constructor options of `Reflector`.
  237. *
  238. * @typedef {Object} Reflector~Options
  239. * @property {number|Color|string} [color=0x7F7F7F] - The reflector's color.
  240. * @property {number} [textureWidth=512] - The texture width. A higher value results in more clear reflections but is also more expensive.
  241. * @property {number} [textureHeight=512] - The texture height. A higher value results in more clear reflections but is also more expensive.
  242. * @property {number} [clipBias=0] - The clip bias.
  243. * @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.
  244. * @property {number} [multisample=4] - How many samples to use for MSAA. `0` disables MSAA.
  245. **/
  246. export { Reflector };
粤ICP备19079148号