Refractor.js 9.9 KB

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