webgl_shadow_contact.html 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316
  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <title>three.js webgl - contact shadows</title>
  5. <meta charset="utf-8">
  6. <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">
  7. <link type="text/css" rel="stylesheet" href="main.css">
  8. <style>
  9. body {
  10. background-color: #fff;
  11. color: #000;
  12. }
  13. a {
  14. color: #08f;
  15. }
  16. </style>
  17. </head>
  18. <body>
  19. <div id="info">
  20. <a href="https://threejs.org" target="_blank" rel="noopener">three.js</a> webgl - contact shadows
  21. </div>
  22. <script type="module">
  23. import * as THREE from '../build/three.module.js';
  24. import { OrbitControls } from './jsm/controls/OrbitControls.js';
  25. import Stats from './jsm/libs/stats.module.js';
  26. import { GUI } from './jsm/libs/dat.gui.module.js';
  27. import { HorizontalBlurShader } from './jsm/shaders/HorizontalBlurShader.js';
  28. import { VerticalBlurShader } from './jsm/shaders/VerticalBlurShader.js';
  29. let camera, scene, renderer, stats, gui;
  30. const meshes = [];
  31. const PLANE_WIDTH = 2.5;
  32. const PLANE_HEIGHT = 2.5;
  33. const CAMERA_HEIGHT = 0.3;
  34. const state = {
  35. shadow: {
  36. blur: 3.5,
  37. darkness: 1,
  38. opacity: 1,
  39. },
  40. plane: {
  41. color: '#ffffff',
  42. opacity: 1,
  43. },
  44. showWireframe: false,
  45. };
  46. let shadowGroup, renderTarget, renderTargetBlur, shadowCamera, cameraHelper, depthMaterial, horizontalBlurMaterial, verticalBlurMaterial;
  47. let plane, blurPlane, fillPlane;
  48. init();
  49. animate();
  50. function init() {
  51. camera = new THREE.PerspectiveCamera( 50, window.innerWidth / window.innerHeight, 0.1, 100 );
  52. camera.position.set( 0.5, 1, 2 );
  53. scene = new THREE.Scene();
  54. scene.background = new THREE.Color( 0xffffff );
  55. stats = new Stats();
  56. document.body.appendChild( stats.dom );
  57. window.addEventListener( 'resize', onWindowResize );
  58. // add the example meshes
  59. const geometries = [
  60. new THREE.BoxGeometry( 0.4, 0.4, 0.4 ),
  61. new THREE.IcosahedronGeometry( 0.3 ),
  62. new THREE.TorusKnotGeometry( 0.4, 0.05, 256, 24, 1, 3 )
  63. ];
  64. const material = new THREE.MeshNormalMaterial();
  65. for ( let i = 0, l = geometries.length; i < l; i ++ ) {
  66. const angle = ( i / l ) * Math.PI * 2;
  67. const geometry = geometries[ i ];
  68. const mesh = new THREE.Mesh( geometry, material );
  69. mesh.position.y = 0.1;
  70. mesh.position.x = Math.cos( angle ) / 2.0;
  71. mesh.position.z = Math.sin( angle ) / 2.0;
  72. scene.add( mesh );
  73. meshes.push( mesh );
  74. }
  75. // the container, if you need to move the plane just move this
  76. shadowGroup = new THREE.Group();
  77. shadowGroup.position.y = - 0.3;
  78. scene.add( shadowGroup );
  79. // the render target that will show the shadows in the plane texture
  80. renderTarget = new THREE.WebGLRenderTarget( 512, 512 );
  81. renderTarget.texture.generateMipmaps = false;
  82. // the render target that we will use to blur the first render target
  83. renderTargetBlur = new THREE.WebGLRenderTarget( 512, 512 );
  84. renderTargetBlur.texture.generateMipmaps = false;
  85. // make a plane and make it face up
  86. const planeGeometry = new THREE.PlaneGeometry( PLANE_WIDTH, PLANE_HEIGHT ).rotateX( Math.PI / 2 );
  87. const planeMaterial = new THREE.MeshBasicMaterial( {
  88. map: renderTarget.texture,
  89. opacity: state.shadow.opacity,
  90. transparent: true,
  91. depthWrite: false,
  92. } );
  93. plane = new THREE.Mesh( planeGeometry, planeMaterial );
  94. // make sure it's rendered after the fillPlane
  95. plane.renderOrder = 1;
  96. shadowGroup.add( plane );
  97. // the y from the texture is flipped!
  98. plane.scale.y = - 1;
  99. // the plane onto which to blur the texture
  100. blurPlane = new THREE.Mesh( planeGeometry );
  101. blurPlane.visible = false;
  102. shadowGroup.add( blurPlane );
  103. // the plane with the color of the ground
  104. const fillPlaneMaterial = new THREE.MeshBasicMaterial( {
  105. color: state.plane.color,
  106. opacity: state.plane.opacity,
  107. transparent: true,
  108. depthWrite: false,
  109. } );
  110. fillPlane = new THREE.Mesh( planeGeometry, fillPlaneMaterial );
  111. fillPlane.rotateX( Math.PI );
  112. shadowGroup.add( fillPlane );
  113. // the camera to render the depth material from
  114. shadowCamera = new THREE.OrthographicCamera( - PLANE_WIDTH / 2, PLANE_WIDTH / 2, PLANE_HEIGHT / 2, - PLANE_HEIGHT / 2, 0, CAMERA_HEIGHT );
  115. shadowCamera.rotation.x = Math.PI / 2; // get the camera to look up
  116. shadowGroup.add( shadowCamera );
  117. cameraHelper = new THREE.CameraHelper( shadowCamera );
  118. // like MeshDepthMaterial, but goes from black to transparent
  119. depthMaterial = new THREE.MeshDepthMaterial();
  120. depthMaterial.userData.darkness = { value: state.shadow.darkness };
  121. depthMaterial.onBeforeCompile = function ( shader ) {
  122. shader.uniforms.darkness = depthMaterial.userData.darkness;
  123. shader.fragmentShader = /* glsl */`
  124. uniform float darkness;
  125. ${shader.fragmentShader.replace(
  126. 'gl_FragColor = vec4( vec3( 1.0 - fragCoordZ ), opacity );',
  127. 'gl_FragColor = vec4( vec3( 0.0 ), ( 1.0 - fragCoordZ ) * darkness );'
  128. )}
  129. `;
  130. };
  131. depthMaterial.depthTest = false;
  132. depthMaterial.depthWrite = false;
  133. horizontalBlurMaterial = new THREE.ShaderMaterial( HorizontalBlurShader );
  134. horizontalBlurMaterial.depthTest = false;
  135. verticalBlurMaterial = new THREE.ShaderMaterial( VerticalBlurShader );
  136. verticalBlurMaterial.depthTest = false;
  137. //
  138. gui = new GUI();
  139. const shadowFolder = gui.addFolder( 'shadow' );
  140. shadowFolder.open();
  141. const planeFolder = gui.addFolder( 'plane' );
  142. planeFolder.open();
  143. shadowFolder.add( state.shadow, 'blur', 0, 15, 0.1 );
  144. shadowFolder.add( state.shadow, 'darkness', 1, 5, 0.1 ).onChange( function () {
  145. depthMaterial.userData.darkness.value = state.shadow.darkness;
  146. } );
  147. shadowFolder.add( state.shadow, 'opacity', 0, 1, 0.01 ).onChange( function () {
  148. plane.material.opacity = state.shadow.opacity;
  149. } );
  150. planeFolder.addColor( state.plane, 'color' ).onChange( function () {
  151. fillPlane.material.color = new THREE.Color( state.plane.color );
  152. } );
  153. planeFolder.add( state.plane, 'opacity', 0, 1, 0.01 ).onChange( function () {
  154. fillPlane.material.opacity = state.plane.opacity;
  155. } );
  156. gui.add( state, 'showWireframe', true ).onChange( function () {
  157. if ( state.showWireframe ) {
  158. scene.add( cameraHelper );
  159. } else {
  160. scene.remove( cameraHelper );
  161. }
  162. } );
  163. //
  164. renderer = new THREE.WebGLRenderer( { antialias: true } );
  165. renderer.setPixelRatio( window.devicePixelRatio );
  166. renderer.setSize( window.innerWidth, window.innerHeight );
  167. document.body.appendChild( renderer.domElement );
  168. //
  169. new OrbitControls( camera, renderer.domElement );
  170. }
  171. function onWindowResize() {
  172. camera.aspect = window.innerWidth / window.innerHeight;
  173. camera.updateProjectionMatrix();
  174. renderer.setSize( window.innerWidth, window.innerHeight );
  175. }
  176. // renderTarget --> blurPlane (horizontalBlur) --> renderTargetBlur --> blurPlane (verticalBlur) --> renderTarget
  177. function blurShadow( amount ) {
  178. blurPlane.visible = true;
  179. // blur horizontally and draw in the renderTargetBlur
  180. blurPlane.material = horizontalBlurMaterial;
  181. blurPlane.material.uniforms.tDiffuse.value = renderTarget.texture;
  182. horizontalBlurMaterial.uniforms.h.value = amount * 1 / 256;
  183. renderer.setRenderTarget( renderTargetBlur );
  184. renderer.render( blurPlane, shadowCamera );
  185. // blur vertically and draw in the main renderTarget
  186. blurPlane.material = verticalBlurMaterial;
  187. blurPlane.material.uniforms.tDiffuse.value = renderTargetBlur.texture;
  188. verticalBlurMaterial.uniforms.v.value = amount * 1 / 256;
  189. renderer.setRenderTarget( renderTarget );
  190. renderer.render( blurPlane, shadowCamera );
  191. blurPlane.visible = false;
  192. }
  193. function animate( ) {
  194. requestAnimationFrame( animate );
  195. //
  196. meshes.forEach( mesh => {
  197. mesh.rotation.x += 0.01;
  198. mesh.rotation.y += 0.02;
  199. } );
  200. //
  201. // remove the background
  202. const initialBackground = scene.background;
  203. scene.background = null;
  204. // force the depthMaterial to everything
  205. cameraHelper.visible = false;
  206. scene.overrideMaterial = depthMaterial;
  207. // render to the render target to get the depths
  208. renderer.setRenderTarget( renderTarget );
  209. renderer.render( scene, shadowCamera );
  210. // and reset the override material
  211. scene.overrideMaterial = null;
  212. cameraHelper.visible = true;
  213. blurShadow( state.shadow.blur );
  214. // a second pass to reduce the artifacts
  215. // (0.4 is the minimum blur amout so that the artifacts are gone)
  216. blurShadow( state.shadow.blur * 0.4 );
  217. // reset and render the normal scene
  218. renderer.setRenderTarget( null );
  219. scene.background = initialBackground;
  220. renderer.render( scene, camera );
  221. stats.update();
  222. }
  223. </script>
  224. </body>
  225. </html>