webgl_shadow_contact.html 9.1 KB

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