webgl_shadowmap_pcss.html 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300
  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <title>three.js webgl - percent closer soft-shadows</title>
  5. <meta charset="utf-8">
  6. <meta name="viewport" content="width=device-width, user-scalable=no, minimum-scale=1.0, maximum-scale=1.0">
  7. <link type="text/css" rel="stylesheet" href="main.css">
  8. <style>
  9. body {
  10. background-color: #cce0ff;
  11. color: #000;
  12. }
  13. a {
  14. color: #08f;
  15. }
  16. </style>
  17. </head>
  18. <body>
  19. <div id="info">Percent Closer Soft-Shadows (PCSS) by <a href="http://eduperiment.com">spidersharma03</a></div>
  20. <script type="x-shader/x-fragment" id="PCSS">
  21. #define LIGHT_WORLD_SIZE 0.005
  22. #define LIGHT_FRUSTUM_WIDTH 3.75
  23. #define LIGHT_SIZE_UV (LIGHT_WORLD_SIZE / LIGHT_FRUSTUM_WIDTH)
  24. #define NEAR_PLANE 9.5
  25. #define NUM_SAMPLES 17
  26. #define NUM_RINGS 11
  27. #define BLOCKER_SEARCH_NUM_SAMPLES NUM_SAMPLES
  28. #define PCF_NUM_SAMPLES NUM_SAMPLES
  29. vec2 poissonDisk[NUM_SAMPLES];
  30. void initPoissonSamples( const in vec2 randomSeed ) {
  31. float ANGLE_STEP = PI2 * float( NUM_RINGS ) / float( NUM_SAMPLES );
  32. float INV_NUM_SAMPLES = 1.0 / float( NUM_SAMPLES );
  33. // jsfiddle that shows sample pattern: https://jsfiddle.net/a16ff1p7/
  34. float angle = rand( randomSeed ) * PI2;
  35. float radius = INV_NUM_SAMPLES;
  36. float radiusStep = radius;
  37. for( int i = 0; i < NUM_SAMPLES; i ++ ) {
  38. poissonDisk[i] = vec2( cos( angle ), sin( angle ) ) * pow( radius, 0.75 );
  39. radius += radiusStep;
  40. angle += ANGLE_STEP;
  41. }
  42. }
  43. float penumbraSize( const in float zReceiver, const in float zBlocker ) { // Parallel plane estimation
  44. return (zReceiver - zBlocker) / zBlocker;
  45. }
  46. float findBlocker( sampler2D shadowMap, const in vec2 uv, const in float zReceiver ) {
  47. // This uses similar triangles to compute what
  48. // area of the shadow map we should search
  49. float searchRadius = LIGHT_SIZE_UV * ( zReceiver - NEAR_PLANE ) / zReceiver;
  50. float blockerDepthSum = 0.0;
  51. int numBlockers = 0;
  52. for( int i = 0; i < BLOCKER_SEARCH_NUM_SAMPLES; i++ ) {
  53. float shadowMapDepth = unpackRGBAToDepth(texture2D(shadowMap, uv + poissonDisk[i] * searchRadius));
  54. if ( shadowMapDepth < zReceiver ) {
  55. blockerDepthSum += shadowMapDepth;
  56. numBlockers ++;
  57. }
  58. }
  59. if( numBlockers == 0 ) return -1.0;
  60. return blockerDepthSum / float( numBlockers );
  61. }
  62. float PCF_Filter(sampler2D shadowMap, vec2 uv, float zReceiver, float filterRadius ) {
  63. float sum = 0.0;
  64. for( int i = 0; i < PCF_NUM_SAMPLES; i ++ ) {
  65. float depth = unpackRGBAToDepth( texture2D( shadowMap, uv + poissonDisk[ i ] * filterRadius ) );
  66. if( zReceiver <= depth ) sum += 1.0;
  67. }
  68. for( int i = 0; i < PCF_NUM_SAMPLES; i ++ ) {
  69. float depth = unpackRGBAToDepth( texture2D( shadowMap, uv + -poissonDisk[ i ].yx * filterRadius ) );
  70. if( zReceiver <= depth ) sum += 1.0;
  71. }
  72. return sum / ( 2.0 * float( PCF_NUM_SAMPLES ) );
  73. }
  74. float PCSS ( sampler2D shadowMap, vec4 coords ) {
  75. vec2 uv = coords.xy;
  76. float zReceiver = coords.z; // Assumed to be eye-space z in this code
  77. initPoissonSamples( uv );
  78. // STEP 1: blocker search
  79. float avgBlockerDepth = findBlocker( shadowMap, uv, zReceiver );
  80. //There are no occluders so early out (this saves filtering)
  81. if( avgBlockerDepth == -1.0 ) return 1.0;
  82. // STEP 2: penumbra size
  83. float penumbraRatio = penumbraSize( zReceiver, avgBlockerDepth );
  84. float filterRadius = penumbraRatio * LIGHT_SIZE_UV * NEAR_PLANE / zReceiver;
  85. // STEP 3: filtering
  86. //return avgBlockerDepth;
  87. return PCF_Filter( shadowMap, uv, zReceiver, filterRadius );
  88. }
  89. </script>
  90. <script type="x-shader/x-fragment" id="PCSSGetShadow">
  91. return PCSS( shadowMap, shadowCoord );
  92. </script>
  93. <script type="module">
  94. import * as THREE from '../build/three.module.js';
  95. import Stats from './jsm/libs/stats.module.js';
  96. import { OrbitControls } from './jsm/controls/OrbitControls.js';
  97. var container, stats;
  98. var camera, scene, renderer;
  99. var group;
  100. init();
  101. animate();
  102. function init() {
  103. container = document.createElement( 'div' );
  104. document.body.appendChild( container );
  105. // scene
  106. scene = new THREE.Scene();
  107. scene.fog = new THREE.Fog( 0xcce0ff, 5, 100 );
  108. // camera
  109. camera = new THREE.PerspectiveCamera( 30, window.innerWidth / window.innerHeight, 1, 10000 );
  110. // We use this particular camera position in order to expose a bug that can sometimes happen presumably
  111. // due to lack of precision when interpolating values over really large triangles.
  112. // It reproduced on at least NVIDIA GTX 1080 and GTX 1050 Ti GPUs when the ground plane was not
  113. // subdivided into segments.
  114. camera.position.x = 7;
  115. camera.position.y = 13;
  116. camera.position.z = 7;
  117. scene.add( camera );
  118. // lights
  119. scene.add( new THREE.AmbientLight( 0x666666 ) );
  120. var light = new THREE.DirectionalLight( 0xdfebff, 1.75 );
  121. light.position.set( 2, 8, 4 );
  122. light.castShadow = true;
  123. light.shadow.mapSize.width = 1024;
  124. light.shadow.mapSize.height = 1024;
  125. light.shadow.camera.far = 20;
  126. scene.add( light );
  127. // scene.add( new DirectionalLightHelper( light ) );
  128. scene.add( new THREE.CameraHelper( light.shadow.camera ) );
  129. // group
  130. group = new THREE.Group();
  131. scene.add( group );
  132. var geometry = new THREE.SphereBufferGeometry( 0.3, 20, 20 );
  133. for ( var i = 0; i < 20; i ++ ) {
  134. var material = new THREE.MeshPhongMaterial( { color: Math.random() * 0xffffff } );
  135. var sphere = new THREE.Mesh( geometry, material );
  136. sphere.position.x = Math.random() - 0.5;
  137. sphere.position.z = Math.random() - 0.5;
  138. sphere.position.normalize();
  139. sphere.position.multiplyScalar( Math.random() * 2 + 1 );
  140. sphere.castShadow = true;
  141. sphere.receiveShadow = true;
  142. sphere.userData.phase = Math.random() * Math.PI;
  143. group.add( sphere );
  144. }
  145. // ground
  146. var groundMaterial = new THREE.MeshPhongMaterial( { color: 0x404040, specular: 0x111111 } );
  147. var mesh = new THREE.Mesh( new THREE.PlaneBufferGeometry( 20000, 20000, 8, 8 ), groundMaterial );
  148. mesh.rotation.x = - Math.PI / 2;
  149. mesh.receiveShadow = true;
  150. scene.add( mesh );
  151. // column
  152. var mesh = new THREE.Mesh( new THREE.BoxBufferGeometry( 1, 4, 1 ), groundMaterial );
  153. mesh.position.y = 2;
  154. mesh.castShadow = true;
  155. mesh.receiveShadow = true;
  156. scene.add( mesh );
  157. // overwrite shadowmap code
  158. var shader = THREE.ShaderChunk.shadowmap_pars_fragment;
  159. shader = shader.replace(
  160. '#ifdef USE_SHADOWMAP',
  161. '#ifdef USE_SHADOWMAP' +
  162. document.getElementById( 'PCSS' ).textContent
  163. );
  164. shader = shader.replace(
  165. '#if defined( SHADOWMAP_TYPE_PCF )',
  166. document.getElementById( 'PCSSGetShadow' ).textContent +
  167. '#if defined( SHADOWMAP_TYPE_PCF )'
  168. );
  169. THREE.ShaderChunk.shadowmap_pars_fragment = shader;
  170. // renderer
  171. renderer = new THREE.WebGLRenderer( { antialias: true } );
  172. renderer.setPixelRatio( window.devicePixelRatio );
  173. renderer.setSize( window.innerWidth, window.innerHeight );
  174. renderer.setClearColor( scene.fog.color );
  175. container.appendChild( renderer.domElement );
  176. renderer.outputEncoding = THREE.sRGBEncoding;
  177. renderer.shadowMap.enabled = true;
  178. // controls
  179. var controls = new OrbitControls( camera, renderer.domElement );
  180. controls.maxPolarAngle = Math.PI * 0.5;
  181. controls.minDistance = 10;
  182. controls.maxDistance = 75;
  183. controls.target.set( 0, 2.5, 0 );
  184. controls.update();
  185. // performance monitor
  186. stats = new Stats();
  187. container.appendChild( stats.dom );
  188. //
  189. window.addEventListener( 'resize', onWindowResize, false );
  190. }
  191. //
  192. function onWindowResize() {
  193. camera.aspect = window.innerWidth / window.innerHeight;
  194. camera.updateProjectionMatrix();
  195. renderer.setSize( window.innerWidth, window.innerHeight );
  196. }
  197. //
  198. function animate() {
  199. var time = performance.now() / 1000;
  200. group.traverse( function ( child ) {
  201. if ( 'phase' in child.userData ) {
  202. child.position.y = Math.abs( Math.sin( time + child.userData.phase ) ) * 4 + 0.3;
  203. }
  204. } );
  205. renderer.render( scene, camera );
  206. stats.update();
  207. requestAnimationFrame( animate );
  208. }
  209. </script>
  210. </body>
  211. </html>