Refractor.js 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388
  1. import {
  2. Color,
  3. Matrix4,
  4. Mesh,
  5. PerspectiveCamera,
  6. Plane,
  7. Quaternion,
  8. ShaderMaterial,
  9. UniformsUtils,
  10. Vector3,
  11. Vector4,
  12. WebGLRenderTarget,
  13. HalfFloatType
  14. } from 'three';
  15. /**
  16. * Can be used to create a flat, refractive surface like for special
  17. * windows or water effects.
  18. *
  19. * Note that this class can only be used with {@link WebGLRenderer}.
  20. * When using {@link WebGPURenderer}, use {@link viewportSharedTexture}.
  21. *
  22. * ```js
  23. * const geometry = new THREE.PlaneGeometry( 100, 100 );
  24. *
  25. * const refractor = new Refractor( refractorGeometry, {
  26. * color: 0xcbcbcb,
  27. * textureWidth: 1024,
  28. * textureHeight: 1024
  29. * } );
  30. *
  31. * scene.add( refractor );
  32. * ```
  33. *
  34. * @augments Mesh
  35. */
  36. class Refractor extends Mesh {
  37. /**
  38. * Constructs a new refractor.
  39. *
  40. * @param {BufferGeometry} geometry - The refractor's geometry.
  41. * @param {Refractor~Options} [options] - The configuration options.
  42. */
  43. constructor( geometry, options = {} ) {
  44. super( geometry );
  45. /**
  46. * This flag can be used for type testing.
  47. *
  48. * @type {boolean}
  49. * @readonly
  50. * @default true
  51. */
  52. this.isRefractor = true;
  53. this.type = 'Refractor';
  54. /**
  55. * The reflector's virtual camera.
  56. *
  57. * @type {PerspectiveCamera}
  58. */
  59. this.camera = new PerspectiveCamera();
  60. const scope = this;
  61. const color = ( options.color !== undefined ) ? new Color( options.color ) : new Color( 0x7F7F7F );
  62. const textureWidth = options.textureWidth || 512;
  63. const textureHeight = options.textureHeight || 512;
  64. const clipBias = options.clipBias || 0;
  65. const shader = options.shader || Refractor.RefractorShader;
  66. const multisample = ( options.multisample !== undefined ) ? options.multisample : 4;
  67. //
  68. const virtualCamera = this.camera;
  69. virtualCamera.matrixAutoUpdate = false;
  70. virtualCamera.userData.refractor = true;
  71. //
  72. const refractorPlane = new Plane();
  73. const textureMatrix = new Matrix4();
  74. // render target
  75. const renderTarget = new WebGLRenderTarget( textureWidth, textureHeight, { samples: multisample, type: HalfFloatType } );
  76. // material
  77. this.material = new ShaderMaterial( {
  78. name: ( shader.name !== undefined ) ? shader.name : 'unspecified',
  79. uniforms: UniformsUtils.clone( shader.uniforms ),
  80. vertexShader: shader.vertexShader,
  81. fragmentShader: shader.fragmentShader,
  82. transparent: true // ensures, refractors are drawn from farthest to closest
  83. } );
  84. this.material.uniforms[ 'color' ].value = color;
  85. this.material.uniforms[ 'tDiffuse' ].value = renderTarget.texture;
  86. this.material.uniforms[ 'textureMatrix' ].value = textureMatrix;
  87. // functions
  88. const visible = ( function () {
  89. const refractorWorldPosition = new Vector3();
  90. const cameraWorldPosition = new Vector3();
  91. const rotationMatrix = new Matrix4();
  92. const view = new Vector3();
  93. const normal = new Vector3();
  94. return function visible( camera ) {
  95. refractorWorldPosition.setFromMatrixPosition( scope.matrixWorld );
  96. cameraWorldPosition.setFromMatrixPosition( camera.matrixWorld );
  97. view.subVectors( refractorWorldPosition, cameraWorldPosition );
  98. rotationMatrix.extractRotation( scope.matrixWorld );
  99. normal.set( 0, 0, 1 );
  100. normal.applyMatrix4( rotationMatrix );
  101. return view.dot( normal ) < 0;
  102. };
  103. } )();
  104. const updateRefractorPlane = ( function () {
  105. const normal = new Vector3();
  106. const position = new Vector3();
  107. const quaternion = new Quaternion();
  108. const scale = new Vector3();
  109. return function updateRefractorPlane() {
  110. scope.matrixWorld.decompose( position, quaternion, scale );
  111. normal.set( 0, 0, 1 ).applyQuaternion( quaternion ).normalize();
  112. // flip the normal because we want to cull everything above the plane
  113. normal.negate();
  114. refractorPlane.setFromNormalAndCoplanarPoint( normal, position );
  115. };
  116. } )();
  117. const updateVirtualCamera = ( function () {
  118. const clipPlane = new Plane();
  119. const clipVector = new Vector4();
  120. const q = new Vector4();
  121. return function updateVirtualCamera( camera ) {
  122. virtualCamera.matrixWorld.copy( camera.matrixWorld );
  123. virtualCamera.matrixWorldInverse.copy( virtualCamera.matrixWorld ).invert();
  124. virtualCamera.projectionMatrix.copy( camera.projectionMatrix );
  125. virtualCamera.far = camera.far; // used in WebGLBackground
  126. // The following code creates an oblique view frustum for clipping.
  127. // see: Lengyel, Eric. “Oblique View Frustum Depth Projection and Clipping”.
  128. // Journal of Game Development, Vol. 1, No. 2 (2005), Charles River Media, pp. 5–16
  129. clipPlane.copy( refractorPlane );
  130. clipPlane.applyMatrix4( virtualCamera.matrixWorldInverse );
  131. clipVector.set( clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.constant );
  132. // calculate the clip-space corner point opposite the clipping plane and
  133. // transform it into camera space by multiplying it by the inverse of the projection matrix
  134. const projectionMatrix = virtualCamera.projectionMatrix;
  135. q.x = ( Math.sign( clipVector.x ) + projectionMatrix.elements[ 8 ] ) / projectionMatrix.elements[ 0 ];
  136. q.y = ( Math.sign( clipVector.y ) + projectionMatrix.elements[ 9 ] ) / projectionMatrix.elements[ 5 ];
  137. q.z = - 1.0;
  138. q.w = ( 1.0 + projectionMatrix.elements[ 10 ] ) / projectionMatrix.elements[ 14 ];
  139. // calculate the scaled plane vector
  140. clipVector.multiplyScalar( 2.0 / clipVector.dot( q ) );
  141. // replacing the third row of the projection matrix
  142. projectionMatrix.elements[ 2 ] = clipVector.x;
  143. projectionMatrix.elements[ 6 ] = clipVector.y;
  144. projectionMatrix.elements[ 10 ] = clipVector.z + 1.0 - clipBias;
  145. projectionMatrix.elements[ 14 ] = clipVector.w;
  146. };
  147. } )();
  148. // This will update the texture matrix that is used for projective texture mapping in the shader.
  149. // see: http://developer.download.nvidia.com/assets/gamedev/docs/projective_texture_mapping.pdf
  150. function updateTextureMatrix( camera ) {
  151. // this matrix does range mapping to [ 0, 1 ]
  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. // we use "Object Linear Texgen", so we need to multiply the texture matrix T
  159. // (matrix above) with the projection and view matrix of the virtual camera
  160. // and the model matrix of the refractor
  161. textureMatrix.multiply( camera.projectionMatrix );
  162. textureMatrix.multiply( camera.matrixWorldInverse );
  163. textureMatrix.multiply( scope.matrixWorld );
  164. }
  165. //
  166. function render( renderer, scene, camera ) {
  167. scope.visible = false;
  168. const currentRenderTarget = renderer.getRenderTarget();
  169. const currentXrEnabled = renderer.xr.enabled;
  170. const currentShadowAutoUpdate = renderer.shadowMap.autoUpdate;
  171. renderer.xr.enabled = false; // avoid camera modification
  172. renderer.shadowMap.autoUpdate = false; // avoid re-computing shadows
  173. renderer.setRenderTarget( renderTarget );
  174. if ( renderer.autoClear === false ) renderer.clear();
  175. renderer.render( scene, virtualCamera );
  176. renderer.xr.enabled = currentXrEnabled;
  177. renderer.shadowMap.autoUpdate = currentShadowAutoUpdate;
  178. renderer.setRenderTarget( currentRenderTarget );
  179. // restore viewport
  180. const viewport = camera.viewport;
  181. if ( viewport !== undefined ) {
  182. renderer.state.viewport( viewport );
  183. }
  184. scope.visible = true;
  185. }
  186. //
  187. this.onBeforeRender = function ( renderer, scene, camera ) {
  188. // ensure refractors are rendered only once per frame
  189. if ( camera.userData.refractor === true ) return;
  190. // avoid rendering when the refractor is viewed from behind
  191. if ( ! visible( camera ) === true ) return;
  192. // update
  193. updateRefractorPlane();
  194. updateTextureMatrix( camera );
  195. updateVirtualCamera( camera );
  196. render( renderer, scene, camera );
  197. };
  198. /**
  199. * Returns the reflector's internal render target.
  200. *
  201. * @return {WebGLRenderTarget} The internal render target
  202. */
  203. this.getRenderTarget = function () {
  204. return renderTarget;
  205. };
  206. /**
  207. * Frees the GPU-related resources allocated by this instance. Call this
  208. * method whenever this instance is no longer used in your app.
  209. */
  210. this.dispose = function () {
  211. renderTarget.dispose();
  212. scope.material.dispose();
  213. };
  214. }
  215. }
  216. Refractor.RefractorShader = {
  217. name: 'RefractorShader',
  218. uniforms: {
  219. 'color': {
  220. value: null
  221. },
  222. 'tDiffuse': {
  223. value: null
  224. },
  225. 'textureMatrix': {
  226. value: null
  227. }
  228. },
  229. vertexShader: /* glsl */`
  230. uniform mat4 textureMatrix;
  231. varying vec4 vUv;
  232. void main() {
  233. vUv = textureMatrix * vec4( position, 1.0 );
  234. gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );
  235. }`,
  236. fragmentShader: /* glsl */`
  237. uniform vec3 color;
  238. uniform sampler2D tDiffuse;
  239. varying vec4 vUv;
  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. void main() {
  247. vec4 base = texture2DProj( tDiffuse, vUv );
  248. gl_FragColor = vec4( blendOverlay( base.rgb, color ), 1.0 );
  249. #include <tonemapping_fragment>
  250. #include <colorspace_fragment>
  251. }`
  252. };
  253. /**
  254. * Constructor options of `Refractor`.
  255. *
  256. * @typedef {Object} Refractor~Options
  257. * @property {number|Color|string} [color=0x7F7F7F] - The refractor's color.
  258. * @property {number} [textureWidth=512] - The texture width. A higher value results in more clear refractions but is also more expensive.
  259. * @property {number} [textureHeight=512] - The texture height. A higher value results in more clear refractions but is also more expensive.
  260. * @property {number} [clipBias=0] - The clip bias.
  261. * @property {Object} [shader] - Can be used to pass in a custom shader that defines how the refractive view is projected onto the reflector's geometry.
  262. * @property {number} [multisample=4] - How many samples to use for MSAA. `0` disables MSAA.
  263. **/
  264. export { Refractor };
粤ICP备19079148号