webgl_shadow_contact.html 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327
  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. function init() {
  58. camera = new THREE.PerspectiveCamera( 50, window.innerWidth / window.innerHeight, 0.1, 100 );
  59. camera.position.set( 0.5, 1, 2 );
  60. scene = new THREE.Scene();
  61. scene.background = new THREE.Color( 0xffffff );
  62. stats = new Stats();
  63. document.body.appendChild( stats.dom );
  64. window.addEventListener( 'resize', onWindowResize );
  65. // add the example meshes
  66. const geometries = [
  67. new THREE.BoxGeometry( 0.4, 0.4, 0.4 ),
  68. new THREE.IcosahedronGeometry( 0.3 ),
  69. new THREE.TorusKnotGeometry( 0.4, 0.05, 256, 24, 1, 3 )
  70. ];
  71. const material = new THREE.MeshNormalMaterial();
  72. for ( let i = 0, l = geometries.length; i < l; i ++ ) {
  73. const angle = ( i / l ) * Math.PI * 2;
  74. const geometry = geometries[ i ];
  75. const mesh = new THREE.Mesh( geometry, material );
  76. mesh.position.y = 0.1;
  77. mesh.position.x = Math.cos( angle ) / 2.0;
  78. mesh.position.z = Math.sin( angle ) / 2.0;
  79. scene.add( mesh );
  80. meshes.push( mesh );
  81. }
  82. // the container, if you need to move the plane just move this
  83. shadowGroup = new THREE.Group();
  84. shadowGroup.position.y = - 0.3;
  85. scene.add( shadowGroup );
  86. // the render target that will show the shadows in the plane texture
  87. renderTarget = new THREE.WebGLRenderTarget( 512, 512 );
  88. renderTarget.texture.generateMipmaps = false;
  89. // the render target that we will use to blur the first render target
  90. renderTargetBlur = new THREE.WebGLRenderTarget( 512, 512 );
  91. renderTargetBlur.texture.generateMipmaps = false;
  92. // make a plane and make it face up
  93. const planeGeometry = new THREE.PlaneGeometry( PLANE_WIDTH, PLANE_HEIGHT ).rotateX( Math.PI / 2 );
  94. const planeMaterial = new THREE.MeshBasicMaterial( {
  95. map: renderTarget.texture,
  96. opacity: state.shadow.opacity,
  97. transparent: true,
  98. depthWrite: false,
  99. } );
  100. plane = new THREE.Mesh( planeGeometry, planeMaterial );
  101. // make sure it's rendered after the fillPlane
  102. plane.renderOrder = 1;
  103. shadowGroup.add( plane );
  104. // the y from the texture is flipped!
  105. plane.scale.y = - 1;
  106. // the plane onto which to blur the texture
  107. blurPlane = new THREE.Mesh( planeGeometry );
  108. blurPlane.visible = false;
  109. shadowGroup.add( blurPlane );
  110. // the plane with the color of the ground
  111. const fillPlaneMaterial = new THREE.MeshBasicMaterial( {
  112. color: state.plane.color,
  113. opacity: state.plane.opacity,
  114. transparent: true,
  115. depthWrite: false,
  116. } );
  117. fillPlane = new THREE.Mesh( planeGeometry, fillPlaneMaterial );
  118. fillPlane.rotateX( Math.PI );
  119. shadowGroup.add( fillPlane );
  120. // the camera to render the depth material from
  121. shadowCamera = new THREE.OrthographicCamera( - PLANE_WIDTH / 2, PLANE_WIDTH / 2, PLANE_HEIGHT / 2, - PLANE_HEIGHT / 2, 0, CAMERA_HEIGHT );
  122. shadowCamera.rotation.x = Math.PI / 2; // get the camera to look up
  123. shadowGroup.add( shadowCamera );
  124. cameraHelper = new THREE.CameraHelper( shadowCamera );
  125. // like MeshDepthMaterial, but goes from black to transparent
  126. depthMaterial = new THREE.MeshDepthMaterial();
  127. depthMaterial.userData.darkness = { value: state.shadow.darkness };
  128. depthMaterial.onBeforeCompile = function ( shader ) {
  129. shader.uniforms.darkness = depthMaterial.userData.darkness;
  130. shader.fragmentShader = /* glsl */`
  131. uniform float darkness;
  132. ${shader.fragmentShader.replace(
  133. 'gl_FragColor = vec4( vec3( 1.0 - fragCoordZ ), opacity );',
  134. 'gl_FragColor = vec4( vec3( 0.0 ), ( 1.0 - fragCoordZ ) * darkness );'
  135. )}
  136. `;
  137. };
  138. depthMaterial.depthTest = false;
  139. depthMaterial.depthWrite = false;
  140. horizontalBlurMaterial = new THREE.ShaderMaterial( HorizontalBlurShader );
  141. horizontalBlurMaterial.depthTest = false;
  142. verticalBlurMaterial = new THREE.ShaderMaterial( VerticalBlurShader );
  143. verticalBlurMaterial.depthTest = false;
  144. //
  145. gui = new GUI();
  146. const shadowFolder = gui.addFolder( 'shadow' );
  147. shadowFolder.open();
  148. const planeFolder = gui.addFolder( 'plane' );
  149. planeFolder.open();
  150. shadowFolder.add( state.shadow, 'blur', 0, 15, 0.1 );
  151. shadowFolder.add( state.shadow, 'darkness', 1, 5, 0.1 ).onChange( function () {
  152. depthMaterial.userData.darkness.value = state.shadow.darkness;
  153. } );
  154. shadowFolder.add( state.shadow, 'opacity', 0, 1, 0.01 ).onChange( function () {
  155. plane.material.opacity = state.shadow.opacity;
  156. } );
  157. planeFolder.addColor( state.plane, 'color' ).onChange( function () {
  158. fillPlane.material.color = new THREE.Color( state.plane.color );
  159. } );
  160. planeFolder.add( state.plane, 'opacity', 0, 1, 0.01 ).onChange( function () {
  161. fillPlane.material.opacity = state.plane.opacity;
  162. } );
  163. gui.add( state, 'showWireframe' ).onChange( function () {
  164. if ( state.showWireframe ) {
  165. scene.add( cameraHelper );
  166. } else {
  167. scene.remove( cameraHelper );
  168. }
  169. } );
  170. //
  171. renderer = new THREE.WebGLRenderer( { antialias: true } );
  172. renderer.setPixelRatio( window.devicePixelRatio );
  173. renderer.setSize( window.innerWidth, window.innerHeight );
  174. renderer.setAnimationLoop( animate );
  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. meshes.forEach( mesh => {
  203. mesh.rotation.x += 0.01;
  204. mesh.rotation.y += 0.02;
  205. } );
  206. //
  207. // remove the background
  208. const initialBackground = scene.background;
  209. scene.background = null;
  210. // force the depthMaterial to everything
  211. cameraHelper.visible = false;
  212. scene.overrideMaterial = depthMaterial;
  213. // set renderer clear alpha
  214. const initialClearAlpha = renderer.getClearAlpha();
  215. renderer.setClearAlpha( 0 );
  216. // render to the render target to get the depths
  217. renderer.setRenderTarget( renderTarget );
  218. renderer.render( scene, shadowCamera );
  219. // and reset the override material
  220. scene.overrideMaterial = null;
  221. cameraHelper.visible = true;
  222. blurShadow( state.shadow.blur );
  223. // a second pass to reduce the artifacts
  224. // (0.4 is the minimum blur amout so that the artifacts are gone)
  225. blurShadow( state.shadow.blur * 0.4 );
  226. // reset and render the normal scene
  227. renderer.setRenderTarget( null );
  228. renderer.setClearAlpha( initialClearAlpha );
  229. scene.background = initialBackground;
  230. renderer.render( scene, camera );
  231. stats.update();
  232. }
  233. </script>
  234. </body>
  235. </html>