webgl_shadowmap_pcss.html 8.6 KB

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