scenegraph.html 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509
  1. Title: Three.js Scene Graph
  2. Description: What's a scene graph?
  3. TOC: Scenegraph
  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 you might want to consider starting there.
  7. Three.js's core is arguably its scene graph. A scene graph in a 3D
  8. engine is a hierarchy of nodes in a graph where each node represents
  9. a local space.
  10. <img src="resources/images/scenegraph-generic.svg" align="center">
  11. That's kind of abstract so let's try to give some examples.
  12. One example might be solar system, sun, earth, moon.
  13. <img src="resources/images/scenegraph-solarsystem.svg" align="center">
  14. The Earth orbits the Sun. The Moon orbits the Earth. The Moon
  15. moves in a circle around the Earth. From the Moon's point of
  16. view it's rotating in the "local space" of the Earth. Even though
  17. its motion relative to the Sun is some crazy spirograph like
  18. curve from the Moon's point of view it just has to concern itself with rotating
  19. around the Earth's local space.
  20. {{{diagram url="resources/moon-orbit.html" }}}
  21. To think of it another way, you living on the Earth do not have to think
  22. about the Earth's rotation on its axis nor its rotation around the
  23. Sun. You just walk or drive or swim or run as though the Earth is
  24. not moving or rotating at all. You walk, drive, swim, run, and live
  25. in the Earth's "local space" even though relative to the sun you are
  26. spinning around the earth at around 1000 miles per hour and around
  27. the sun at around 67,000 miles per hour. Your position in the solar
  28. system is similar to that of the moon above but you don't have to concern
  29. yourself. You just worry about your position relative to the earth in its
  30. "local space".
  31. Let's take it one step at a time. Imagine we want to make
  32. a diagram of the sun, earth, and moon. We'll start with the sun by
  33. just making a sphere and putting it at the origin. Note: We're using
  34. sun, earth, moon as a demonstration of how to use a scene graph. Of course
  35. the real sun, earth, and moon use physics but for our purposes we'll
  36. fake it with a scene graph.
  37. ```js
  38. // an array of objects whose rotation to update
  39. const objects = [];
  40. // use just one sphere for everything
  41. const radius = 1;
  42. const widthSegments = 6;
  43. const heightSegments = 6;
  44. const sphereGeometry = new THREE.SphereGeometry(
  45. radius, widthSegments, heightSegments);
  46. const sunMaterial = new THREE.MeshPhongMaterial({emissive: 0xFFFF00});
  47. const sunMesh = new THREE.Mesh(sphereGeometry, sunMaterial);
  48. sunMesh.scale.set(5, 5, 5); // make the sun large
  49. scene.add(sunMesh);
  50. objects.push(sunMesh);
  51. ```
  52. We're using a really low-polygon sphere. Only 6 subdivisions around its equator.
  53. This is so it's easy to see the rotation.
  54. We're going to reuse the same sphere for everything so we'll set a scale
  55. for the sun mesh of 5x.
  56. We also set the phong material's `emissive` property to yellow. A phong material's
  57. emissive property is basically the color that will be drawn with no light hitting
  58. the surface. Light is added to that color.
  59. Let's also put a single point light in the center of the scene. We'll go into more
  60. details about point lights later but for now the simple version is a point light
  61. represents light that emanates from a single point.
  62. ```js
  63. {
  64. const color = 0xFFFFFF;
  65. const intensity = 3;
  66. const light = new THREE.PointLight(color, intensity);
  67. scene.add(light);
  68. }
  69. ```
  70. To make it easy to see we're going to put the camera directly above the origin
  71. looking down. The easiest way to do that is to use the `lookAt` function. The `lookAt`
  72. function will orient the camera from its position to "look at" the position
  73. we pass to `lookAt`. Before we do that though we need to tell the camera
  74. which way the top of the camera is facing or rather which way is "up" for the
  75. camera. For most situations positive Y being up is good enough but since
  76. we are looking straight down we need to tell the camera that positive Z is up.
  77. ```js
  78. const camera = new THREE.PerspectiveCamera(fov, aspect, near, far);
  79. camera.position.set(0, 50, 0);
  80. camera.up.set(0, 0, 1);
  81. camera.lookAt(0, 0, 0);
  82. ```
  83. In the render loop, adapted from previous examples, we're rotating all
  84. objects in our `objects` array with this code.
  85. ```js
  86. objects.forEach((obj) => {
  87. obj.rotation.y = time;
  88. });
  89. ```
  90. Since we added the `sunMesh` to the `objects` array it will rotate.
  91. {{{example url="../threejs-scenegraph-sun.html" }}}
  92. Now let's add in the earth.
  93. ```js
  94. const earthMaterial = new THREE.MeshPhongMaterial({color: 0x2233FF, emissive: 0x112244});
  95. const earthMesh = new THREE.Mesh(sphereGeometry, earthMaterial);
  96. earthMesh.position.x = 10;
  97. scene.add(earthMesh);
  98. objects.push(earthMesh);
  99. ```
  100. We make a material that is blue but we gave it a small amount of *emissive* blue
  101. so that it will show up against our black background.
  102. We use the same `sphereGeometry` with our new blue `earthMaterial` to make
  103. an `earthMesh`. We position that 10 units to the left of the sun
  104. and add it to the scene. Since we added it to our `objects` array it will
  105. rotate too.
  106. {{{example url="../threejs-scenegraph-sun-earth.html" }}}
  107. You can see both the sun and the earth are rotating but the earth is not
  108. going around the sun. Let's make the earth a child of the sun
  109. ```js
  110. -scene.add(earthMesh);
  111. +sunMesh.add(earthMesh);
  112. ```
  113. and...
  114. {{{example url="../threejs-scenegraph-sun-earth-orbit.html" }}}
  115. What happened? Why is the earth the same size as the sun and why is it so far away?
  116. I actually had to move the camera from 50 units above to 150 units above to see the earth.
  117. We made the `earthMesh` a child of the `sunMesh`. The `sunMesh` has
  118. its scale set to 5x with `sunMesh.scale.set(5, 5, 5)`. That means the
  119. `sunMesh`s local space is 5 times as big. Anything put in that space
  120. will be multiplied by 5. That means the earth is now 5x larger and
  121. its distance from the sun (`earthMesh.position.x = 10`) is also
  122. 5x as well.
  123. Our scene graph currently looks like this
  124. <img src="resources/images/scenegraph-sun-earth.svg" align="center">
  125. To fix it let's add an empty scene graph node. We'll parent both the sun and the earth
  126. to that node.
  127. ```js
  128. +const solarSystem = new THREE.Object3D();
  129. +scene.add(solarSystem);
  130. +objects.push(solarSystem);
  131. const sunMaterial = new THREE.MeshPhongMaterial({emissive: 0xFFFF00});
  132. const sunMesh = new THREE.Mesh(sphereGeometry, sunMaterial);
  133. sunMesh.scale.set(5, 5, 5);
  134. -scene.add(sunMesh);
  135. +solarSystem.add(sunMesh);
  136. objects.push(sunMesh);
  137. const earthMaterial = new THREE.MeshPhongMaterial({color: 0x2233FF, emissive: 0x112244});
  138. const earthMesh = new THREE.Mesh(sphereGeometry, earthMaterial);
  139. earthMesh.position.x = 10;
  140. -sunMesh.add(earthMesh);
  141. +solarSystem.add(earthMesh);
  142. objects.push(earthMesh);
  143. ```
  144. Here we made an `Object3D`. Like a `Mesh` it is also a node in the scene graph
  145. but unlike a `Mesh` it has no material or geometry. It just represents a local space.
  146. Our new scene graph looks like this
  147. <img src="resources/images/scenegraph-sun-earth-fixed.svg" align="center">
  148. Both the `sunMesh` and the `earthMesh` are children of the `solarSystem`. All 3
  149. are being rotated and now because the `earthMesh` is not a child of the `sunMesh`
  150. it is no longer scaled by 5x.
  151. {{{example url="../threejs-scenegraph-sun-earth-orbit-fixed.html" }}}
  152. Much better. The earth is smaller than the sun and it's rotating around the sun
  153. and rotating itself.
  154. Continuing that same pattern let's add a moon.
  155. ```js
  156. +const earthOrbit = new THREE.Object3D();
  157. +earthOrbit.position.x = 10;
  158. +solarSystem.add(earthOrbit);
  159. +objects.push(earthOrbit);
  160. const earthMaterial = new THREE.MeshPhongMaterial({color: 0x2233FF, emissive: 0x112244});
  161. const earthMesh = new THREE.Mesh(sphereGeometry, earthMaterial);
  162. -earthMesh.position.x = 10; // note that this offset is already set in its parent's THREE.Object3D object "earthOrbit"
  163. -solarSystem.add(earthMesh);
  164. +earthOrbit.add(earthMesh);
  165. objects.push(earthMesh);
  166. +const moonOrbit = new THREE.Object3D();
  167. +moonOrbit.position.x = 2;
  168. +earthOrbit.add(moonOrbit);
  169. +const moonMaterial = new THREE.MeshPhongMaterial({color: 0x888888, emissive: 0x222222});
  170. +const moonMesh = new THREE.Mesh(sphereGeometry, moonMaterial);
  171. +moonMesh.scale.set(.5, .5, .5);
  172. +moonOrbit.add(moonMesh);
  173. +objects.push(moonMesh);
  174. ```
  175. Again we added more invisible scene graph nodes. The first, an `Object3D` called `earthOrbit`
  176. and added both the `earthMesh` and the `moonOrbit` to it, also new. We then added the `moonMesh`
  177. to the `moonOrbit`. The new scene graph looks like this.
  178. <img src="resources/images/scenegraph-sun-earth-moon.svg" align="center">
  179. and here's that
  180. {{{example url="../threejs-scenegraph-sun-earth-moon.html" }}}
  181. You can see the moon follows the spirograph pattern shown at the top
  182. of this article but we didn't have to manually compute it. We just
  183. setup our scene graph to do it for us.
  184. It is often useful to draw something to visualize the nodes in the scene graph.
  185. Three.js has some helpful ummmm, helpers to ummm, ... help with this.
  186. One is called an `AxesHelper`. It draws 3 lines representing the local
  187. <span style="color:red">X</span>,
  188. <span style="color:green">Y</span>, and
  189. <span style="color:blue">Z</span> axes. Let's add one to every node we
  190. created.
  191. ```js
  192. // add an AxesHelper to each node
  193. objects.forEach((node) => {
  194. const axes = new THREE.AxesHelper();
  195. axes.material.depthTest = false;
  196. axes.renderOrder = 1;
  197. node.add(axes);
  198. });
  199. ```
  200. On our case we want the axes to appear even though they are inside the spheres.
  201. To do this we set their material's `depthTest` to false which means they will
  202. not check to see if they are drawing behind something else. We also
  203. set their `renderOrder` to 1 (the default is 0) so that they get drawn after
  204. all the spheres. Otherwise a sphere might draw over them and cover them up.
  205. {{{example url="../threejs-scenegraph-sun-earth-moon-axes.html" }}}
  206. We can see the
  207. <span style="color:red">x (red)</span> and
  208. <span style="color:blue">z (blue)</span> axes. Since we are looking
  209. straight down and each of our objects is only rotating around its
  210. y axis we don't see much of the <span style="color:green">y (green)</span> axes.
  211. It might be hard to see some of them as there are 2 pairs of overlapping axes. Both the `sunMesh`
  212. and the `solarSystem` are at the same position. Similarly the `earthMesh` and
  213. `earthOrbit` are at the same position. Let's add some simple controls to allow us
  214. to turn them on/off for each node.
  215. While we're at it let's also add another helper called the `GridHelper`. It
  216. makes a 2D grid on the X,Z plane. By default the grid is 10x10 units.
  217. We're also going to use [dat.GUI](https://github.com/dataarts/dat.gui) which is
  218. a UI library that is very popular with three.js projects. dat.GUI takes an
  219. object and a property name on that object and based on the type of the property
  220. automatically makes a UI to manipulate that property.
  221. We want to make both a `GridHelper` and an `AxesHelper` for each node. We need
  222. a label for each node so we'll get rid of the old loop and switch to calling
  223. some function to add the helpers for each node
  224. ```js
  225. -// add an AxesHelper to each node
  226. -objects.forEach((node) => {
  227. - const axes = new THREE.AxesHelper();
  228. - axes.material.depthTest = false;
  229. - axes.renderOrder = 1;
  230. - node.add(axes);
  231. -});
  232. +function makeAxisGrid(node, label, units) {
  233. + const helper = new AxisGridHelper(node, units);
  234. + gui.add(helper, 'visible').name(label);
  235. +}
  236. +
  237. +makeAxisGrid(solarSystem, 'solarSystem', 25);
  238. +makeAxisGrid(sunMesh, 'sunMesh');
  239. +makeAxisGrid(earthOrbit, 'earthOrbit');
  240. +makeAxisGrid(earthMesh, 'earthMesh');
  241. +makeAxisGrid(moonOrbit, 'moonOrbit');
  242. +makeAxisGrid(moonMesh, 'moonMesh');
  243. ```
  244. `makeAxisGrid` makes an `AxisGridHelper` which is a class we'll create
  245. to make dat.GUI happy. Like it says above dat.GUI
  246. will automagically make a UI that manipulates the named property
  247. of some object. It will create a different UI depending on the type
  248. of property. We want it to create a checkbox so we need to specify
  249. a `bool` property. But, we want both the axes and the grid
  250. to appear/disappear based on a single property so we'll make a class
  251. that has a getter and setter for a property. That way we can let dat.GUI
  252. think it's manipulating a single property but internally we can set
  253. the visible property of both the `AxesHelper` and `GridHelper` for a node.
  254. ```js
  255. // Turns both axes and grid visible on/off
  256. // dat.GUI requires a property that returns a bool
  257. // to decide to make a checkbox so we make a setter
  258. // and getter for `visible` which we can tell dat.GUI
  259. // to look at.
  260. class AxisGridHelper {
  261. constructor(node, units = 10) {
  262. const axes = new THREE.AxesHelper();
  263. axes.material.depthTest = false;
  264. axes.renderOrder = 2; // after the grid
  265. node.add(axes);
  266. const grid = new THREE.GridHelper(units, units);
  267. grid.material.depthTest = false;
  268. grid.renderOrder = 1;
  269. node.add(grid);
  270. this.grid = grid;
  271. this.axes = axes;
  272. this.visible = false;
  273. }
  274. get visible() {
  275. return this._visible;
  276. }
  277. set visible(v) {
  278. this._visible = v;
  279. this.grid.visible = v;
  280. this.axes.visible = v;
  281. }
  282. }
  283. ```
  284. One thing to notice is we set the `renderOrder` of the `AxesHelper`
  285. to 2 and for the `GridHelper` to 1 so that the axes get drawn after the grid.
  286. Otherwise the grid might overwrite the axes.
  287. {{{example url="../threejs-scenegraph-sun-earth-moon-axes-grids.html" }}}
  288. Turn on the `solarSystem` and you'll see how the earth is exactly 10
  289. units out from the center just like we set above. You can see how the
  290. earth is in the *local space* of the `solarSystem`. Similarly if you
  291. turn on the `earthOrbit` you'll see how the moon is exactly 2 units
  292. from the center of the *local space* of the `earthOrbit`.
  293. A few more examples of scene graphs. An automobile in a simple game world might have a scene graph like this
  294. <img src="resources/images/scenegraph-car.svg" align="center">
  295. If you move the car's body all the wheels will move with it. If you wanted the body
  296. to bounce separate from the wheels you might parent the body and the wheels to a "frame" node
  297. that represents the car's frame.
  298. Another example is a human in a game world.
  299. <img src="resources/images/scenegraph-human.svg" align="center">
  300. You can see the scene graph gets pretty complex for a human. In fact
  301. that scene graph above is simplified. For example you might extend it
  302. to cover every finger (at least another 28 nodes) and every toe
  303. (yet another 28 nodes) plus ones for the face and jaw, the eyes and maybe more.
  304. Let's make one semi-complex scene graph. We'll make a tank. The tank will have
  305. 6 wheels and a turret. The tank will follow a path. There will be a sphere that
  306. moves around and the tank will target the sphere.
  307. Here's the scene graph. The meshes are colored in green, the `Object3D`s in blue,
  308. the lights in gold, and the cameras in purple. One camera has not been added
  309. to the scene graph.
  310. <div class="threejs_center"><img src="resources/images/scenegraph-tank.svg" style="width: 800px;"></div>
  311. Look in the code to see the setup of all of these nodes.
  312. For the target, the thing the tank is aiming at, there is a `targetOrbit`
  313. (`Object3D`) which just rotates similar to the `earthOrbit` above. A
  314. `targetElevation` (`Object3D`) which is a child of the `targetOrbit` provides an
  315. offset from the `targetOrbit` and a base elevation. Childed to that is another
  316. `Object3D` called `targetBob` which just bobs up and down relative to the
  317. `targetElevation`. Finally there's the `targetMesh` which is just a cube we
  318. rotate and change its colors
  319. ```js
  320. // move target
  321. targetOrbit.rotation.y = time * .27;
  322. targetBob.position.y = Math.sin(time * 2) * 4;
  323. targetMesh.rotation.x = time * 7;
  324. targetMesh.rotation.y = time * 13;
  325. targetMaterial.emissive.setHSL(time * 10 % 1, 1, .25);
  326. targetMaterial.color.setHSL(time * 10 % 1, 1, .25);
  327. ```
  328. For the tank there's an `Object3D` called `tank` which is used to move everything
  329. below it around. The code uses a `SplineCurve` which it can ask for positions
  330. along that curve. 0.0 is the start of the curve. 1.0 is the end of the curve. It
  331. asks for the current position where it puts the tank. It then asks for a
  332. position slightly further down the curve and uses that to point the tank in that
  333. direction using `Object3D.lookAt`.
  334. ```js
  335. const tankPosition = new THREE.Vector2();
  336. const tankTarget = new THREE.Vector2();
  337. ...
  338. // move tank
  339. const tankTime = time * .05;
  340. curve.getPointAt(tankTime % 1, tankPosition);
  341. curve.getPointAt((tankTime + 0.01) % 1, tankTarget);
  342. tank.position.set(tankPosition.x, 0, tankPosition.y);
  343. tank.lookAt(tankTarget.x, 0, tankTarget.y);
  344. ```
  345. The turret on top of the tank is moved automatically by being a child
  346. of the tank. To point it at the target we just ask for the target's world position
  347. and then again use `Object3D.lookAt`
  348. ```js
  349. const targetPosition = new THREE.Vector3();
  350. ...
  351. // face turret at target
  352. targetMesh.getWorldPosition(targetPosition);
  353. turretPivot.lookAt(targetPosition);
  354. ```
  355. There's a `turretCamera` which is a child of the `turretMesh` so
  356. it will move up and down and rotate with the turret. We make that
  357. aim at the target.
  358. ```js
  359. // make the turretCamera look at target
  360. turretCamera.lookAt(targetPosition);
  361. ```
  362. There is also a `targetCameraPivot` which is a child of `targetBob` so it floats
  363. around with the target. We aim that back at the tank. Its purpose is to allow the
  364. `targetCamera` to be offset from the target itself. If we instead made the camera
  365. a child of `targetBob` and just aimed the camera itself it would be inside the
  366. target.
  367. ```js
  368. // make the targetCameraPivot look at the tank
  369. tank.getWorldPosition(targetPosition);
  370. targetCameraPivot.lookAt(targetPosition);
  371. ```
  372. Finally we rotate all the wheels
  373. ```js
  374. wheelMeshes.forEach((obj) => {
  375. obj.rotation.x = time * 3;
  376. });
  377. ```
  378. For the cameras we setup an array of all 4 cameras at init time with descriptions.
  379. ```js
  380. const cameras = [
  381. { cam: camera, desc: 'detached camera', },
  382. { cam: turretCamera, desc: 'on turret looking at target', },
  383. { cam: targetCamera, desc: 'near target looking at tank', },
  384. { cam: tankCamera, desc: 'above back of tank', },
  385. ];
  386. const infoElem = document.querySelector('#info');
  387. ```
  388. and cycle through our cameras at render time.
  389. ```js
  390. const camera = cameras[time * .25 % cameras.length | 0];
  391. infoElem.textContent = camera.desc;
  392. ```
  393. {{{example url="../threejs-scenegraph-tank.html"}}}
  394. I hope this gives some idea of how scene graphs work and how you might use them.
  395. Making `Object3D` nodes and parenting things to them is an important step to using
  396. a 3D engine like three.js well. Often it might seem like some complex math is necessary
  397. to make something move and rotate the way you want. For example without a scene graph
  398. computing the motion of the moon or where to put the wheels of the car relative to its
  399. body would be very complicated but using a scene graph it becomes much easier.
  400. [Next up we'll go over materials](threejs-materials.html).