optimize-lots-of-objects.html 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535
  1. Title: Three.js Optimize Lots of Objects
  2. Description: Optimize by merging Objects
  3. TOC: Optimizing Lots of Objects
  4. This article is part of a series of articles about three.js. The first article
  5. is [three.js fundamentals](threejs-fundamentals.html). If you haven't read that
  6. yet and you're new to three.js you might want to consider starting there.
  7. There are many ways to optimize things for three.js. One way is often referred
  8. to as *merging geometry*. Every `Mesh` you create and three.js represents 1 or
  9. more requests by the system to draw something. Drawing 2 things has more
  10. overhead than drawing 1 even if the results are the same so one way to optimize
  11. is to merge meshes.
  12. Let's show an example of when this is a good solution for an issue. Let's
  13. re-create the [WebGL Globe](https://globe.chromeexperiments.com/).
  14. The first thing we need to do is get some data. The WebGL Globe said the data
  15. they use comes from [SEDAC](http://sedac.ciesin.columbia.edu/gpw/). Checking out
  16. the site I saw there was [demographic data in a grid
  17. format](https://beta.sedac.ciesin.columbia.edu/data/set/gpw-v4-basic-demographic-characteristics-rev10).
  18. I downloaded the data at 60 minute resolution. Then I took a look at the data
  19. It looks like this
  20. ```txt
  21. ncols 360
  22. nrows 145
  23. xllcorner -180
  24. yllcorner -60
  25. cellsize 0.99999999999994
  26. NODATA_value -9999
  27. -9999 -9999 -9999 -9999 -9999 -9999 -9999 -9999 -9999 -9999 -9999 -9999 ...
  28. -9999 -9999 -9999 -9999 -9999 -9999 -9999 -9999 -9999 -9999 -9999 -9999 ...
  29. -9999 -9999 -9999 -9999 -9999 -9999 -9999 -9999 -9999 -9999 -9999 -9999 ...
  30. -9999 -9999 -9999 -9999 -9999 -9999 -9999 -9999 -9999 -9999 -9999 -9999 ...
  31. -9999 -9999 -9999 -9999 -9999 -9999 -9999 -9999 -9999 -9999 -9999 -9999 ...
  32. -9999 -9999 -9999 -9999 -9999 -9999 -9999 -9999 -9999 -9999 -9999 -9999 ...
  33. -9999 -9999 -9999 -9999 -9999 -9999 -9999 -9999 -9999 -9999 -9999 -9999 ...
  34. -9999 -9999 -9999 -9999 -9999 -9999 -9999 -9999 -9999 -9999 -9999 -9999 ...
  35. -9999 -9999 -9999 -9999 -9999 -9999 -9999 -9999 -9999 -9999 -9999 -9999 ...
  36. -9999 -9999 -9999 -9999 -9999 -9999 -9999 -9999 -9999 -9999 -9999 -9999 ...
  37. -9999 -9999 -9999 -9999 -9999 -9999 -9999 -9999 -9999 -9999 -9999 -9999 ...
  38. -9999 -9999 -9999 -9999 -9999 -9999 -9999 -9999 -9999 -9999 -9999 -9999 ...
  39. -9999 -9999 -9999 -9999 -9999 -9999 -9999 -9999 -9999 -9999 -9999 -9999 ...
  40. 9.241768 8.790958 2.095345 -9999 0.05114867 -9999 -9999 -9999 -9999 -999...
  41. 1.287993 0.4395509 -9999 -9999 -9999 -9999 -9999 -9999 -9999 -9999 -9999...
  42. -9999 -9999 -9999 -9999 -9999 -9999 -9999 -9999 -9999 -9999 -9999 -9999 ...
  43. ```
  44. There's a few lines that are like key/value pairs followed by lines with a value
  45. per grid point, one line for each row of data points.
  46. To make sure we understand the data let's try to plot it in 2D.
  47. First some code to load the text file
  48. ```js
  49. async function loadFile(url) {
  50. const res = await fetch(url);
  51. return res.text();
  52. }
  53. ```
  54. The code above returns a `Promise` with the contents of the file at `url`;
  55. Then we need some code to parse the file
  56. ```js
  57. function parseData(text) {
  58. const data = [];
  59. const settings = {data};
  60. let max;
  61. let min;
  62. // split into lines
  63. text.split('\n').forEach((line) => {
  64. // split the line by whitespace
  65. const parts = line.trim().split(/\s+/);
  66. if (parts.length === 2) {
  67. // only 2 parts, must be a key/value pair
  68. settings[parts[0]] = parseFloat(parts[1]);
  69. } else if (parts.length > 2) {
  70. // more than 2 parts, must be data
  71. const values = parts.map((v) => {
  72. const value = parseFloat(v);
  73. if (value === settings.NODATA_value) {
  74. return undefined;
  75. }
  76. max = Math.max(max === undefined ? value : max, value);
  77. min = Math.min(min === undefined ? value : min, value);
  78. return value;
  79. });
  80. data.push(values);
  81. }
  82. });
  83. return Object.assign(settings, {min, max});
  84. }
  85. ```
  86. The code above returns an object with all the key/value pairs from the file as
  87. well as a `data` property with all the data in one large array and the `min` and
  88. `max` values found in the data.
  89. Then we need some code to draw that data
  90. ```js
  91. function drawData(file) {
  92. const {min, max, data} = file;
  93. const range = max - min;
  94. const ctx = document.querySelector('canvas').getContext('2d');
  95. // make the canvas the same size as the data
  96. ctx.canvas.width = ncols;
  97. ctx.canvas.height = nrows;
  98. // but display it double size so it's not too small
  99. ctx.canvas.style.width = px(ncols * 2);
  100. ctx.canvas.style.height = px(nrows * 2);
  101. // fill the canvas to dark gray
  102. ctx.fillStyle = '#444';
  103. ctx.fillRect(0, 0, ctx.canvas.width, ctx.canvas.height);
  104. // draw each data point
  105. data.forEach((row, latNdx) => {
  106. row.forEach((value, lonNdx) => {
  107. if (value === undefined) {
  108. return;
  109. }
  110. const amount = (value - min) / range;
  111. const hue = 1;
  112. const saturation = 1;
  113. const lightness = amount;
  114. ctx.fillStyle = hsl(hue, saturation, lightness);
  115. ctx.fillRect(lonNdx, latNdx, 1, 1);
  116. });
  117. });
  118. }
  119. function px(v) {
  120. return `${v | 0}px`;
  121. }
  122. function hsl(h, s, l) {
  123. return `hsl(${h * 360 | 0},${s * 100 | 0}%,${l * 100 | 0}%)`;
  124. }
  125. ```
  126. And finally gluing it all together
  127. ```js
  128. loadFile('resources/data/gpw/gpw_v4_basic_demographic_characteristics_rev10_a000_014mt_2010_cntm_1_deg.asc')
  129. .then(parseData)
  130. .then(drawData);
  131. ```
  132. Gives us this result
  133. {{{example url="../gpw-data-viewer.html" }}}
  134. So that seems to work.
  135. Let's try it in 3D. Starting with the code from [rendering on
  136. demand](threejs-rendering-on-demand.html) We'll make one box per data in the
  137. file.
  138. First let's make a simple sphere with a texture of the world. Here's the texture
  139. <div class="threejs_center"><img src="../resources/images/world.jpg" style="width: 600px"></div>
  140. And the code to set it up.
  141. ```js
  142. {
  143. const loader = new THREE.TextureLoader();
  144. const texture = loader.load('resources/images/world.jpg', render);
  145. const geometry = new THREE.SphereGeometry(1, 64, 32);
  146. const material = new THREE.MeshBasicMaterial({map: texture});
  147. scene.add(new THREE.Mesh(geometry, material));
  148. }
  149. ```
  150. Notice the call to `render` when the texture has finished loading. We need this
  151. because we're [rendering on demand](threejs-rendering-on-demand.html) instead of
  152. continuously so we need to render once when the texture is loaded.
  153. Then we need to change the code that drew a dot per data point above to instead
  154. make a box per data point.
  155. ```js
  156. function addBoxes(file) {
  157. const {min, max, data} = file;
  158. const range = max - min;
  159. // make one box geometry
  160. const boxWidth = 1;
  161. const boxHeight = 1;
  162. const boxDepth = 1;
  163. const geometry = new THREE.BoxGeometry(boxWidth, boxHeight, boxDepth);
  164. // make it so it scales away from the positive Z axis
  165. geometry.applyMatrix4(new THREE.Matrix4().makeTranslation(0, 0, 0.5));
  166. // these helpers will make it easy to position the boxes
  167. // We can rotate the lon helper on its Y axis to the longitude
  168. const lonHelper = new THREE.Object3D();
  169. scene.add(lonHelper);
  170. // We rotate the latHelper on its X axis to the latitude
  171. const latHelper = new THREE.Object3D();
  172. lonHelper.add(latHelper);
  173. // The position helper moves the object to the edge of the sphere
  174. const positionHelper = new THREE.Object3D();
  175. positionHelper.position.z = 1;
  176. latHelper.add(positionHelper);
  177. const lonFudge = Math.PI * .5;
  178. const latFudge = Math.PI * -0.135;
  179. data.forEach((row, latNdx) => {
  180. row.forEach((value, lonNdx) => {
  181. if (value === undefined) {
  182. return;
  183. }
  184. const amount = (value - min) / range;
  185. const material = new THREE.MeshBasicMaterial();
  186. const hue = THREE.MathUtils.lerp(0.7, 0.3, amount);
  187. const saturation = 1;
  188. const lightness = THREE.MathUtils.lerp(0.1, 1.0, amount);
  189. material.color.setHSL(hue, saturation, lightness);
  190. const mesh = new THREE.Mesh(geometry, material);
  191. scene.add(mesh);
  192. // adjust the helpers to point to the latitude and longitude
  193. lonHelper.rotation.y = THREE.MathUtils.degToRad(lonNdx + file.xllcorner) + lonFudge;
  194. latHelper.rotation.x = THREE.MathUtils.degToRad(latNdx + file.yllcorner) + latFudge;
  195. // use the world matrix of the position helper to
  196. // position this mesh.
  197. positionHelper.updateWorldMatrix(true, false);
  198. mesh.applyMatrix4(positionHelper.matrixWorld);
  199. mesh.scale.set(0.005, 0.005, THREE.MathUtils.lerp(0.01, 0.5, amount));
  200. });
  201. });
  202. }
  203. ```
  204. The code is mostly straight forward from our test drawing code.
  205. We make one box and adjust its center so it scales away from positive Z. If we
  206. didn't do this it would scale from the center but we want them to grow away from the origin.
  207. <div class="spread">
  208. <div>
  209. <div data-diagram="scaleCenter" style="height: 250px"></div>
  210. <div class="code">default</div>
  211. </div>
  212. <div>
  213. <div data-diagram="scalePositiveZ" style="height: 250px"></div>
  214. <div class="code">adjusted</div>
  215. </div>
  216. </div>
  217. Of course we could also solve that by parenting the box to more `THREE.Object3D`
  218. objects like we covered in [scene graphs](threejs-scenegraph.html) but the more
  219. nodes we add to a scene graph the slower it gets.
  220. We also setup this small hierarchy of nodes of `lonHelper`, `latHelper`, and
  221. `positionHelper`. We use these objects to compute a position around the sphere
  222. were to place the box.
  223. <div class="spread">
  224. <div data-diagram="lonLatPos" style="width: 600px; height: 400px;"></div>
  225. </div>
  226. Above the <span style="color: green;">green bar</span> represents `lonHelper` and
  227. is used to rotate toward longitude on the equator. The <span style="color: blue;">
  228. blue bar</span> represents `latHelper` which is used to rotate to a
  229. latitude above or below the equator. The <span style="color: red;">red
  230. sphere</span> represents the offset that that `positionHelper` provides.
  231. We could do all of the math manually to figure out positions on the globe but
  232. doing it this way leaves most of the math to the library itself so we don't need
  233. to deal with.
  234. For each data point we create a `MeshBasicMaterial` and a `Mesh` and then we ask
  235. for the world matrix of the `positionHelper` and apply that to the new `Mesh`.
  236. Finally we scale the mesh at its new position.
  237. Like above, we could also have created a `latHelper`, `lonHelper`, and
  238. `positionHelper` for every new box but that would be even slower.
  239. There are up to 360x145 boxes we're going to create. That's up to 52000 boxes.
  240. Because some data points are marked as "NO_DATA" the actual number of boxes
  241. we're going to create is around 19000. If we added 3 extra helper objects per
  242. box that would be nearly 80000 scene graph nodes that THREE.js would have to
  243. compute positions for. By instead using one set of helpers to just position the
  244. meshes we save around 60000 operations.
  245. A note about `lonFudge` and `latFudge`. `lonFudge` is π/2 which is a quarter of a turn.
  246. That makes sense. It just means the texture or texture coordinates start at a
  247. different offset around the globe. `latFudge` on the other hand I have no idea
  248. why it needs to be π * -0.135, that's just an amount that made the boxes line up
  249. with the texture.
  250. The last thing we need to do is call our loader
  251. ```
  252. loadFile('resources/data/gpw/gpw_v4_basic_demographic_characteristics_rev10_a000_014mt_2010_cntm_1_deg.asc')
  253. .then(parseData)
  254. - .then(drawData)
  255. + .then(addBoxes)
  256. + .then(render);
  257. ```
  258. Once the data has finished loading and parsing then we need to render at least
  259. once since we're [rendering on demand](threejs-rendering-on-demand.html).
  260. {{{example url="../threejs-lots-of-objects-slow.html" }}}
  261. If you try to rotate the example above by dragging on the sample you'll likely
  262. notice it's slow.
  263. We can check the framerate by [opening the
  264. devtools](threejs-debugging-javascript.html) and turning on the browser's frame
  265. rate meter.
  266. <div class="threejs_center"><img src="resources/images/bring-up-fps-meter.gif"></div>
  267. On my machine I see a framerate under 20fps.
  268. <div class="threejs_center"><img src="resources/images/fps-meter.gif"></div>
  269. That doesn't feel very good to me and I suspect many people have slower machines
  270. which would make it even worse. We'd better look into optimizing.
  271. For this particular problem we can merge all the boxes into a single geometry.
  272. We're currently drawing around 19000 boxes. By merging them into a single
  273. geometry we'd remove 18999 operations.
  274. Here's the new code to merge the boxes into a single geometry.
  275. ```js
  276. function addBoxes(file) {
  277. const {min, max, data} = file;
  278. const range = max - min;
  279. - // make one box geometry
  280. - const boxWidth = 1;
  281. - const boxHeight = 1;
  282. - const boxDepth = 1;
  283. - const geometry = new THREE.BoxGeometry(boxWidth, boxHeight, boxDepth);
  284. - // make it so it scales away from the positive Z axis
  285. - geometry.applyMatrix4(new THREE.Matrix4().makeTranslation(0, 0, 0.5));
  286. // these helpers will make it easy to position the boxes
  287. // We can rotate the lon helper on its Y axis to the longitude
  288. const lonHelper = new THREE.Object3D();
  289. scene.add(lonHelper);
  290. // We rotate the latHelper on its X axis to the latitude
  291. const latHelper = new THREE.Object3D();
  292. lonHelper.add(latHelper);
  293. // The position helper moves the object to the edge of the sphere
  294. const positionHelper = new THREE.Object3D();
  295. positionHelper.position.z = 1;
  296. latHelper.add(positionHelper);
  297. + // Used to move the center of the box so it scales from the position Z axis
  298. + const originHelper = new THREE.Object3D();
  299. + originHelper.position.z = 0.5;
  300. + positionHelper.add(originHelper);
  301. const lonFudge = Math.PI * .5;
  302. const latFudge = Math.PI * -0.135;
  303. + const geometries = [];
  304. data.forEach((row, latNdx) => {
  305. row.forEach((value, lonNdx) => {
  306. if (value === undefined) {
  307. return;
  308. }
  309. const amount = (value - min) / range;
  310. - const material = new THREE.MeshBasicMaterial();
  311. - const hue = THREE.MathUtils.lerp(0.7, 0.3, amount);
  312. - const saturation = 1;
  313. - const lightness = THREE.MathUtils.lerp(0.1, 1.0, amount);
  314. - material.color.setHSL(hue, saturation, lightness);
  315. - const mesh = new THREE.Mesh(geometry, material);
  316. - scene.add(mesh);
  317. + const boxWidth = 1;
  318. + const boxHeight = 1;
  319. + const boxDepth = 1;
  320. + const geometry = new THREE.BoxGeometry(boxWidth, boxHeight, boxDepth);
  321. // adjust the helpers to point to the latitude and longitude
  322. lonHelper.rotation.y = THREE.MathUtils.degToRad(lonNdx + file.xllcorner) + lonFudge;
  323. latHelper.rotation.x = THREE.MathUtils.degToRad(latNdx + file.yllcorner) + latFudge;
  324. - // use the world matrix of the position helper to
  325. - // position this mesh.
  326. - positionHelper.updateWorldMatrix(true, false);
  327. - mesh.applyMatrix4(positionHelper.matrixWorld);
  328. -
  329. - mesh.scale.set(0.005, 0.005, THREE.MathUtils.lerp(0.01, 0.5, amount));
  330. + // use the world matrix of the origin helper to
  331. + // position this geometry
  332. + positionHelper.scale.set(0.005, 0.005, THREE.MathUtils.lerp(0.01, 0.5, amount));
  333. + originHelper.updateWorldMatrix(true, false);
  334. + geometry.applyMatrix4(originHelper.matrixWorld);
  335. +
  336. + geometries.push(geometry);
  337. });
  338. });
  339. + const mergedGeometry = BufferGeometryUtils.mergeBufferGeometries(
  340. + geometries, false);
  341. + const material = new THREE.MeshBasicMaterial({color:'red'});
  342. + const mesh = new THREE.Mesh(mergedGeometry, material);
  343. + scene.add(mesh);
  344. }
  345. ```
  346. Above we removed the code that was changing the box geometry's center point and
  347. are instead doing it by adding an `originHelper`. Before we were using the same
  348. geometry 19000 times. This time we are creating new geometry for every single
  349. box and since we are going to use `applyMatrix` to move the vertices of each box
  350. geometry we might as well do it once instead of twice.
  351. At the end we pass an array of all the geometries to
  352. `BufferGeometryUtils.mergeBufferGeometries` which will combined all of
  353. them into a single mesh.
  354. We also need to include the `BufferGeometryUtils`
  355. ```js
  356. import * as BufferGeometryUtils from './resources/threejs/r132/examples/jsm/utils/BufferGeometryUtils.js';
  357. ```
  358. And now, at least on my machine, I get 60 frames per second
  359. {{{example url="../threejs-lots-of-objects-merged.html" }}}
  360. So that worked but because it's one mesh we only get one material which means we
  361. only get one color where as before we had a different color on each box. We can
  362. fix that by using vertex colors.
  363. Vertex colors add a color per vertex. By setting all the colors of each vertex
  364. of each box to specific colors every box will have a different color.
  365. ```js
  366. +const color = new THREE.Color();
  367. const lonFudge = Math.PI * .5;
  368. const latFudge = Math.PI * -0.135;
  369. const geometries = [];
  370. data.forEach((row, latNdx) => {
  371. row.forEach((value, lonNdx) => {
  372. if (value === undefined) {
  373. return;
  374. }
  375. const amount = (value - min) / range;
  376. const boxWidth = 1;
  377. const boxHeight = 1;
  378. const boxDepth = 1;
  379. const geometry = new THREE.BoxGeometry(boxWidth, boxHeight, boxDepth);
  380. // adjust the helpers to point to the latitude and longitude
  381. lonHelper.rotation.y = THREE.MathUtils.degToRad(lonNdx + file.xllcorner) + lonFudge;
  382. latHelper.rotation.x = THREE.MathUtils.degToRad(latNdx + file.yllcorner) + latFudge;
  383. // use the world matrix of the origin helper to
  384. // position this geometry
  385. positionHelper.scale.set(0.005, 0.005, THREE.MathUtils.lerp(0.01, 0.5, amount));
  386. originHelper.updateWorldMatrix(true, false);
  387. geometry.applyMatrix4(originHelper.matrixWorld);
  388. + // compute a color
  389. + const hue = THREE.MathUtils.lerp(0.7, 0.3, amount);
  390. + const saturation = 1;
  391. + const lightness = THREE.MathUtils.lerp(0.4, 1.0, amount);
  392. + color.setHSL(hue, saturation, lightness);
  393. + // get the colors as an array of values from 0 to 255
  394. + const rgb = color.toArray().map(v => v * 255);
  395. +
  396. + // make an array to store colors for each vertex
  397. + const numVerts = geometry.getAttribute('position').count;
  398. + const itemSize = 3; // r, g, b
  399. + const colors = new Uint8Array(itemSize * numVerts);
  400. +
  401. + // copy the color into the colors array for each vertex
  402. + colors.forEach((v, ndx) => {
  403. + colors[ndx] = rgb[ndx % 3];
  404. + });
  405. +
  406. + const normalized = true;
  407. + const colorAttrib = new THREE.BufferAttribute(colors, itemSize, normalized);
  408. + geometry.setAttribute('color', colorAttrib);
  409. geometries.push(geometry);
  410. });
  411. });
  412. ```
  413. The code above looks up the number or vertices needed by getting the `position`
  414. attribute from the geometry. We then create a `Uint8Array` to put the colors in.
  415. It then adds that as an attribute by calling `geometry.setAttribute`.
  416. Lastly we need to tell three.js to use the vertex colors.
  417. ```js
  418. const mergedGeometry = BufferGeometryUtils.mergeBufferGeometries(
  419. geometries, false);
  420. -const material = new THREE.MeshBasicMaterial({color:'red'});
  421. +const material = new THREE.MeshBasicMaterial({
  422. + vertexColors: true,
  423. +});
  424. const mesh = new THREE.Mesh(mergedGeometry, material);
  425. scene.add(mesh);
  426. ```
  427. And with that we get our colors back
  428. {{{example url="../threejs-lots-of-objects-merged-vertexcolors.html" }}}
  429. Merging geometry is a common optimization technique. For example rather than
  430. 100 trees you might merge the trees into 1 geometry, a pile of individual rocks
  431. into a single geometry of rocks, a picket fence from individual pickets into
  432. one fence mesh. Another example in Minecraft it doesn't likely draw each cube
  433. individually but rather creates groups of merged cubes and also selectively removing
  434. faces that are never visible.
  435. The problem with making everything one mesh though is it's no longer easy
  436. to move any part that was previously separate. Depending on our use case
  437. though there are creative solutions. We'll explore one in
  438. [another article](threejs-optimize-lots-of-objects-animated.html).
  439. <canvas id="c"></canvas>
  440. <script type="module" src="resources/threejs-lots-of-objects.js"></script>