optimize-lots-of-objects.html 25 KB

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