shadows.html 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504
  1. Title: Three.js Shadows
  2. Description: Shadows in Three.js
  3. TOC: Shadows
  4. This article is part of a series of articles about three.js. The
  5. first article is [three.js fundamentals](threejs-fundamentals.html). If
  6. you haven't read that yet and you're new to three.js you might want to
  7. consider starting there. The
  8. [previous article was about cameras](threejs-cameras.html) which is
  9. important to have read before you read this article as well as
  10. the [article before that one about lights](threejs-lights.html).
  11. Shadows on computers can be a complicated topic. There are various
  12. solutions and all of them have tradeoffs including the solutions
  13. available in three.js.
  14. Three.js by default uses *shadow maps*. The way a shadow map works
  15. is, *for every light that casts shadows all objects marked to cast
  16. shadows are rendered from the point of view of the light*. **READ THAT
  17. AGAIN!** and let it sink in.
  18. In other words, if you have 20 objects, and 5 lights, and
  19. all 20 objects are casting shadows and all 5 lights are casting
  20. shadows then your entire scene will be drawn 6 times. All 20 objects
  21. will be drawn for light #1, then all 20 objects will be drawn for
  22. light #2, then #3, etc and finally the actual scene will be drawn
  23. using data from the first 5 renders.
  24. It gets worse, if you have a point light casting shadows the scene
  25. has to be drawn 6 times just for that light!
  26. For these reasons it's common to find other solutions than to have
  27. a bunch of lights all generating shadows. One common solution
  28. is to have multiple lights but only one directional light generating
  29. shadows.
  30. Yet another solution is to use lightmaps and or ambient occlusion maps
  31. to pre-compute the effects of lighting offline. This results in static
  32. lighting or static lighting hints but at least it's fast. We'll
  33. cover both of those in another article.
  34. Another solution is to use fake shadows. Make a plane, put a grayscale
  35. texture in the plane that approximates a shadow,
  36. draw it above the ground below your object.
  37. For example let's use this texture as a fake shadow
  38. <div class="threejs_center"><img src="../resources/images/roundshadow.png"></div>
  39. We'll use some of the code from [the previous article](threejs-cameras.html).
  40. Let's set the background color to white.
  41. ```js
  42. const scene = new THREE.Scene();
  43. +scene.background = new THREE.Color('white');
  44. ```
  45. Then we'll setup the same checkerboard ground but this time it's using
  46. a `MeshBasicMaterial` as we don't need lighting for the ground.
  47. ```js
  48. +const loader = new THREE.TextureLoader();
  49. {
  50. const planeSize = 40;
  51. - const loader = new THREE.TextureLoader();
  52. const texture = loader.load('resources/images/checker.png');
  53. texture.wrapS = THREE.RepeatWrapping;
  54. texture.wrapT = THREE.RepeatWrapping;
  55. texture.magFilter = THREE.NearestFilter;
  56. const repeats = planeSize / 2;
  57. texture.repeat.set(repeats, repeats);
  58. const planeGeo = new THREE.PlaneGeometry(planeSize, planeSize);
  59. const planeMat = new THREE.MeshBasicMaterial({
  60. map: texture,
  61. side: THREE.DoubleSide,
  62. });
  63. + planeMat.color.setRGB(1.5, 1.5, 1.5);
  64. const mesh = new THREE.Mesh(planeGeo, planeMat);
  65. mesh.rotation.x = Math.PI * -.5;
  66. scene.add(mesh);
  67. }
  68. ```
  69. Note we're setting the color to `1.5, 1.5, 1.5`. This will multiply the checkerboard
  70. texture's colors by 1.5, 1.5, 1.5. Since the texture's colors are 0x808080 and 0xC0C0C0
  71. which is medium gray and light gray, multiplying them by 1.5 will give us a white and
  72. light grey checkerboard.
  73. Let's load the shadow texture
  74. ```js
  75. const shadowTexture = loader.load('resources/images/roundshadow.png');
  76. ```
  77. and make an array to remember each sphere and associated objects.
  78. ```js
  79. const sphereShadowBases = [];
  80. ```
  81. Then we'll make a sphere geometry
  82. ```js
  83. const sphereRadius = 1;
  84. const sphereWidthDivisions = 32;
  85. const sphereHeightDivisions = 16;
  86. const sphereGeo = new THREE.SphereGeometry(sphereRadius, sphereWidthDivisions, sphereHeightDivisions);
  87. ```
  88. And a plane geometry for the fake shadow
  89. ```js
  90. const planeSize = 1;
  91. const shadowGeo = new THREE.PlaneGeometry(planeSize, planeSize);
  92. ```
  93. Now we'll make a bunch of spheres. For each sphere we'll create a `base`
  94. `THREE.Object3D` and we'll make both the shadow plane mesh and the sphere mesh
  95. children of the base. That way if we move the base both the sphere and the shadow
  96. will move. We need to put the shadow slightly above the ground to prevent z-fighting.
  97. We also set `depthWrite` to false so that the shadows don't mess each other up.
  98. We'll go over both of these issues in [another article](threejs-transparency.html).
  99. The shadow is a `MeshBasicMaterial` because it doesn't need lighting.
  100. We make each sphere a different hue and then save off the base, the sphere mesh,
  101. the shadow mesh and the initial y position of each sphere.
  102. ```js
  103. const numSpheres = 15;
  104. for (let i = 0; i < numSpheres; ++i) {
  105. // make a base for the shadow and the sphere
  106. // so they move together.
  107. const base = new THREE.Object3D();
  108. scene.add(base);
  109. // add the shadow to the base
  110. // note: we make a new material for each sphere
  111. // so we can set that sphere's material transparency
  112. // separately.
  113. const shadowMat = new THREE.MeshBasicMaterial({
  114. map: shadowTexture,
  115. transparent: true, // so we can see the ground
  116. depthWrite: false, // so we don't have to sort
  117. });
  118. const shadowMesh = new THREE.Mesh(shadowGeo, shadowMat);
  119. shadowMesh.position.y = 0.001; // so we're above the ground slightly
  120. shadowMesh.rotation.x = Math.PI * -.5;
  121. const shadowSize = sphereRadius * 4;
  122. shadowMesh.scale.set(shadowSize, shadowSize, shadowSize);
  123. base.add(shadowMesh);
  124. // add the sphere to the base
  125. const u = i / numSpheres; // goes from 0 to 1 as we iterate the spheres.
  126. const sphereMat = new THREE.MeshPhongMaterial();
  127. sphereMat.color.setHSL(u, 1, .75);
  128. const sphereMesh = new THREE.Mesh(sphereGeo, sphereMat);
  129. sphereMesh.position.set(0, sphereRadius + 2, 0);
  130. base.add(sphereMesh);
  131. // remember all 3 plus the y position
  132. sphereShadowBases.push({base, sphereMesh, shadowMesh, y: sphereMesh.position.y});
  133. }
  134. ```
  135. We setup 2 lights. One is a `HemisphereLight` with the intensity set to 2 to really
  136. brighten things up.
  137. ```js
  138. {
  139. const skyColor = 0xB1E1FF; // light blue
  140. const groundColor = 0xB97A20; // brownish orange
  141. const intensity = 2;
  142. const light = new THREE.HemisphereLight(skyColor, groundColor, intensity);
  143. scene.add(light);
  144. }
  145. ```
  146. The other is a `DirectionalLight` so the spheres get some definition
  147. ```js
  148. {
  149. const color = 0xFFFFFF;
  150. const intensity = 1;
  151. const light = new THREE.DirectionalLight(color, intensity);
  152. light.position.set(0, 10, 5);
  153. light.target.position.set(-5, 0, 0);
  154. scene.add(light);
  155. scene.add(light.target);
  156. }
  157. ```
  158. It would render as is but let's animate there spheres.
  159. For each sphere, shadow, base set we move the base in the xz plane, we
  160. move the sphere up and down using `Math.abs(Math.sin(time))`
  161. which gives us a bouncy animation. And, we also set the shadow material's
  162. opacity so that as each sphere goes higher its shadow fades out.
  163. ```js
  164. function render(time) {
  165. time *= 0.001; // convert to seconds
  166. ...
  167. sphereShadowBases.forEach((sphereShadowBase, ndx) => {
  168. const {base, sphereMesh, shadowMesh, y} = sphereShadowBase;
  169. // u is a value that goes from 0 to 1 as we iterate the spheres
  170. const u = ndx / sphereShadowBases.length;
  171. // compute a position for the base. This will move
  172. // both the sphere and its shadow
  173. const speed = time * .2;
  174. const angle = speed + u * Math.PI * 2 * (ndx % 1 ? 1 : -1);
  175. const radius = Math.sin(speed - ndx) * 10;
  176. base.position.set(Math.cos(angle) * radius, 0, Math.sin(angle) * radius);
  177. // yOff is a value that goes from 0 to 1
  178. const yOff = Math.abs(Math.sin(time * 2 + ndx));
  179. // move the sphere up and down
  180. sphereMesh.position.y = y + THREE.MathUtils.lerp(-2, 2, yOff);
  181. // fade the shadow as the sphere goes up
  182. shadowMesh.material.opacity = THREE.MathUtils.lerp(1, .25, yOff);
  183. });
  184. ...
  185. ```
  186. And here's 15 kind of bouncing balls.
  187. {{{example url="../threejs-shadows-fake.html" }}}
  188. In some apps it's common to use a round or oval shadow for everything but
  189. of course you could also use different shaped shadow textures. You might also
  190. give the shadow a harder edge. A good example of using this type
  191. of shadow is [Animal Crossing Pocket Camp](https://www.google.com/search?tbm=isch&q=animal+crossing+pocket+camp+screenshots)
  192. where you can see each character has a simple round shadow. It's effective and cheap.
  193. [Monument Valley](https://www.google.com/search?q=monument+valley+screenshots&tbm=isch)
  194. appears to also use this kind of shadow for the main character.
  195. So, moving on to shadow maps, there are 3 lights which can cast shadows. The `DirectionalLight`,
  196. the `PointLight`, and the `SpotLight`.
  197. Let's start with the `DirectionalLight` with the helper example from [the lights article](threejs-lights.html).
  198. The first thing we need to do is turn on shadows in the renderer.
  199. ```js
  200. const renderer = new THREE.WebGLRenderer({canvas});
  201. +renderer.shadowMap.enabled = true;
  202. ```
  203. Then we also need to tell the light to cast a shadow
  204. ```js
  205. const light = new THREE.DirectionalLight(color, intensity);
  206. +light.castShadow = true;
  207. ```
  208. We also need to go to each mesh in the scene and decide if it should
  209. both cast shadows and/or receive shadows.
  210. Let's make the plane (the ground) only receive shadows since we don't
  211. really care what happens underneath.
  212. ```js
  213. const mesh = new THREE.Mesh(planeGeo, planeMat);
  214. mesh.receiveShadow = true;
  215. ```
  216. For the cube and the sphere let's have them both receive and cast shadows
  217. ```js
  218. const mesh = new THREE.Mesh(cubeGeo, cubeMat);
  219. mesh.castShadow = true;
  220. mesh.receiveShadow = true;
  221. ...
  222. const mesh = new THREE.Mesh(sphereGeo, sphereMat);
  223. mesh.castShadow = true;
  224. mesh.receiveShadow = true;
  225. ```
  226. And then we run it.
  227. {{{example url="../threejs-shadows-directional-light.html" }}}
  228. What happened? Why are parts of the shadows missing?
  229. The reason is shadow maps are created by rendering the scene from the point
  230. of view of the light. In this case there is a camera at the `DirectionalLight`
  231. that is looking at its target. Just like [the camera's we previously covered](threejs-cameras.html)
  232. the light's shadow camera defines an area inside of which
  233. the shadows get rendered. In the example above that area is too small.
  234. In order to visualize that area we can get the light's shadow camera and add
  235. a `CameraHelper` to the scene.
  236. ```js
  237. const cameraHelper = new THREE.CameraHelper(light.shadow.camera);
  238. scene.add(cameraHelper);
  239. ```
  240. And now you can see the area for which shadows are cast and received.
  241. {{{example url="../threejs-shadows-directional-light-with-camera-helper.html" }}}
  242. Adjust the target x value back and forth and it should be pretty clear that only
  243. what's inside the light's shadow camera box is where shadows are drawn.
  244. We can adjust the size of that box by adjusting the light's shadow camera.
  245. Let's add some GUI setting to adjust the light's shadow camera box. Since a
  246. `DirectionalLight` represents light all going in a parallel direction, the
  247. `DirectionalLight` uses an `OrthographicCamera` for its shadow camera.
  248. We went over how an `OrthographicCamera` works in [the previous article about cameras](threejs-cameras.html).
  249. Recall an `OrthographicCamera` defines
  250. its box or *view frustum* by its `left`, `right`, `top`, `bottom`, `near`, `far`,
  251. and `zoom` properties.
  252. Again let's make a helper class for the dat.GUI. We'll make a `DimensionGUIHelper`
  253. that we'll pass an object and 2 properties. It will present one property that dat.GUI
  254. can adjust and in response will set the two properties one positive and one negative.
  255. We can use this to set `left` and `right` as `width` and `up` and `down` as `height`.
  256. ```js
  257. class DimensionGUIHelper {
  258. constructor(obj, minProp, maxProp) {
  259. this.obj = obj;
  260. this.minProp = minProp;
  261. this.maxProp = maxProp;
  262. }
  263. get value() {
  264. return this.obj[this.maxProp] * 2;
  265. }
  266. set value(v) {
  267. this.obj[this.maxProp] = v / 2;
  268. this.obj[this.minProp] = v / -2;
  269. }
  270. }
  271. ```
  272. We'll also use the `MinMaxGUIHelper` we created in the [camera article](threejs-cameras.html)
  273. to adjust `near` and `far`.
  274. ```js
  275. const gui = new GUI();
  276. gui.addColor(new ColorGUIHelper(light, 'color'), 'value').name('color');
  277. gui.add(light, 'intensity', 0, 2, 0.01);
  278. +{
  279. + const folder = gui.addFolder('Shadow Camera');
  280. + folder.open();
  281. + folder.add(new DimensionGUIHelper(light.shadow.camera, 'left', 'right'), 'value', 1, 100)
  282. + .name('width')
  283. + .onChange(updateCamera);
  284. + folder.add(new DimensionGUIHelper(light.shadow.camera, 'bottom', 'top'), 'value', 1, 100)
  285. + .name('height')
  286. + .onChange(updateCamera);
  287. + const minMaxGUIHelper = new MinMaxGUIHelper(light.shadow.camera, 'near', 'far', 0.1);
  288. + folder.add(minMaxGUIHelper, 'min', 0.1, 50, 0.1).name('near').onChange(updateCamera);
  289. + folder.add(minMaxGUIHelper, 'max', 0.1, 50, 0.1).name('far').onChange(updateCamera);
  290. + folder.add(light.shadow.camera, 'zoom', 0.01, 1.5, 0.01).onChange(updateCamera);
  291. +}
  292. ```
  293. We tell the GUI to call our `updateCamera` function anytime anything changes.
  294. Let's write that function to update the light, the helper for the light, the
  295. light's shadow camera, and the helper showing the light's shadow camera.
  296. ```js
  297. function updateCamera() {
  298. // update the light target's matrixWorld because it's needed by the helper
  299. light.target.updateMatrixWorld();
  300. helper.update();
  301. // update the light's shadow camera's projection matrix
  302. light.shadow.camera.updateProjectionMatrix();
  303. // and now update the camera helper we're using to show the light's shadow camera
  304. cameraHelper.update();
  305. }
  306. updateCamera();
  307. ```
  308. And now that we've given the light's shadow camera a GUI we can play with the values.
  309. {{{example url="../threejs-shadows-directional-light-with-camera-gui.html" }}}
  310. Set the `width` and `height` to about 30 and you can see the shadows are correct
  311. and the areas that need to be in shadow for this scene are entirely covered.
  312. But this brings up the question, why not just set `width` and `height` to some
  313. giant numbers to just cover everything? Set the `width` and `height` to 100
  314. and you might see something like this
  315. <div class="threejs_center"><img src="resources/images/low-res-shadow-map.png" style="width: 369px"></div>
  316. What's going on with these low-res shadows?!
  317. This issue is yet another shadow related setting to be aware of.
  318. Shadow maps are textures the shadows get drawn into.
  319. Those textures have a size. The shadow camera's area we set above is stretched
  320. across that size. That means the larger area you set, the more blocky your shadows will
  321. be.
  322. You can set the resolution of the shadow map's texture by setting `light.shadow.mapSize.width`
  323. and `light.shadow.mapSize.height`. They default to 512x512.
  324. The larger you make them the more memory they take and the slower they are to compute so you want
  325. to set them as small as you can and still make your scene work. The same is true with the
  326. light's shadow camera area. Smaller means better looking shadows so make the area as small as you
  327. can and still cover your scene. Be aware that each user's machine has a maximum texture size
  328. allowed which is available on the renderer as [`renderer.capabilities.maxTextureSize`](WebGLRenderer.capabilities).
  329. <!--
  330. Ok but what about `near` and `far` I hear you thinking. Can we set `near` to 0.00001 and far to `100000000`
  331. -->
  332. Switching to the `SpotLight` the light's shadow camera becomes a `PerspectiveCamera`. Unlike the `DirectionalLight`'s shadow camera
  333. where we could manually set most its settings, `SpotLight`'s shadow camera is controlled by the `SpotLight` itself. The `fov` for the shadow
  334. camera is directly connected to the `SpotLight`'s `angle` setting.
  335. The `aspect` is set automatically based on the size of the shadow map.
  336. ```js
  337. -const light = new THREE.DirectionalLight(color, intensity);
  338. +const light = new THREE.SpotLight(color, intensity);
  339. ```
  340. and we added back in the `penumbra` and `angle` settings
  341. from our [article about lights](threejs-lights.html).
  342. {{{example url="../threejs-shadows-spot-light-with-camera-gui.html" }}}
  343. <!--
  344. You can notice, just like the last example if we set the angle high
  345. then the shadow map, the texture is spread over a very large area and
  346. the resolution of our shadows gets really low.
  347. div class="threejs_center"><img src="resources/images/low-res-shadow-map-spotlight.png" style="width: 344px"></div>
  348. You can increase the size of the shadow map as mentioned above. You can
  349. also blur the result
  350. {{{example url="../threejs-shadows-spot-light-with-shadow-radius" }}}
  351. -->
  352. And finally there's shadows with a `PointLight`. Since a `PointLight`
  353. shines in all directions the only relevant settings are `near` and `far`.
  354. Otherwise the `PointLight` shadow is effectively 6 `SpotLight` shadows
  355. each one pointing to the face of a cube around the light. This means
  356. `PointLight` shadows are much slower since the entire scene must be
  357. drawn 6 times, one for each direction.
  358. Let's put a box around our scene so we can see shadows on the walls
  359. and ceiling. We'll set the material's `side` property to `THREE.BackSide`
  360. so we render the inside of the box instead of the outside. Like the floor
  361. we'll set it only to receive shadows. Also we'll set the position of the
  362. box so its bottom is slightly below the floor so the floor and the bottom
  363. of the box don't z-fight.
  364. ```js
  365. {
  366. const cubeSize = 30;
  367. const cubeGeo = new THREE.BoxGeometry(cubeSize, cubeSize, cubeSize);
  368. const cubeMat = new THREE.MeshPhongMaterial({
  369. color: '#CCC',
  370. side: THREE.BackSide,
  371. });
  372. const mesh = new THREE.Mesh(cubeGeo, cubeMat);
  373. mesh.receiveShadow = true;
  374. mesh.position.set(0, cubeSize / 2 - 0.1, 0);
  375. scene.add(mesh);
  376. }
  377. ```
  378. And of course we need to switch the light to a `PointLight`.
  379. ```js
  380. -const light = new THREE.SpotLight(color, intensity);
  381. +const light = new THREE.PointLight(color, intensity);
  382. ....
  383. // so we can easily see where the point light is
  384. +const helper = new THREE.PointLightHelper(light);
  385. +scene.add(helper);
  386. ```
  387. {{{example url="../threejs-shadows-point-light.html" }}}
  388. Use the `position` GUI settings to move the light around
  389. and you'll see the shadows fall on all the walls. You can
  390. also adjust `near` and `far` settings and see just like
  391. the other shadows when things are closer than `near` they
  392. no longer receive a shadow and they are further than `far`
  393. they are always in shadow.
  394. <!--
  395. self shadow, shadow acne
  396. -->
粤ICP备19079148号