optimize-lots-of-objects.html 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460
  1. <!DOCTYPE html><html lang="ja"><head>
  2. <meta charset="utf-8">
  3. <title>で多くのオブジェクトを最適化</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 – で多くのオブジェクトを最適化">
  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>で多くのオブジェクトを最適化</h1>
  18. </div>
  19. <div class="lesson">
  20. <div class="lesson-main">
  21. <p>この記事はthree.jsの連載記事の1つです。最初の記事は<a href="fundamentals.html">Three.jsの基礎知識</a>です。まだ読んでいない場合はそこから始めて下さい。</p>
  22. <p>three.jsには最適化する方法は多々あります。1つの方法は<em>ジオメトリのマージ</em>と呼ばれています。メッシュを作成すると描画リクエストを1つ以上行った事を表します。
  23. 2つのメッシュを描画すると結果が同じでも1つのメッシュを描画するよりもオーバーヘッドが大きく、最適化する1つの方法がメッシュのマージです。</p>
  24. <p>これが問題解決になるか、例を示してみます。
  25. <a href="https://globe.chromeexperiments.com/">WebGL Globe</a>を作り直してみましょう。</p>
  26. <p>まずデータが必要です。WebGL Globeで使用しているデータは<a href="http://sedac.ciesin.columbia.edu/gpw/">SEDAC</a>です。
  27. サイトをチェックすると<a href="https://beta.sedac.ciesin.columbia.edu/data/set/gpw-v4-basic-demographic-characteristics-rev10">人口統計データのグリッド形式</a>があります。
  28. 私は60分間の解像度データをダウンロードしました。データを見てみると以下のような感じになっています。</p>
  29. <pre class="prettyprint showlinemods notranslate lang-txt" translate="no"> ncols 360
  30. nrows 145
  31. xllcorner -180
  32. yllcorner -60
  33. cellsize 0.99999999999994
  34. NODATA_value -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. -9999 -9999 -9999 -9999 -9999 -9999 -9999 -9999 -9999 -9999 -9999 -9999 ...
  41. -9999 -9999 -9999 -9999 -9999 -9999 -9999 -9999 -9999 -9999 -9999 -9999 ...
  42. -9999 -9999 -9999 -9999 -9999 -9999 -9999 -9999 -9999 -9999 -9999 -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. 9.241768 8.790958 2.095345 -9999 0.05114867 -9999 -9999 -9999 -9999 -999...
  49. 1.287993 0.4395509 -9999 -9999 -9999 -9999 -9999 -9999 -9999 -9999 -9999...
  50. -9999 -9999 -9999 -9999 -9999 -9999 -9999 -9999 -9999 -9999 -9999 -9999 ...
  51. </pre>
  52. <p>キーと値のペアのような行がいくつかあり、その行に続くグリッドポイントごとの値の行があり、データポイントごとに1行ずつ並んでいます。
  53. データをもっと理解するために2Dでプロットしてみましょう。</p>
  54. <p>最初にテキストファイルをロードするコードです。</p>
  55. <pre class="prettyprint showlinemods notranslate lang-js" translate="no">async function loadFile(url) {
  56. const res = await fetch(url);
  57. return res.text();
  58. }
  59. </pre>
  60. <p>上記のコードは <code class="notranslate" translate="no">Promise</code> を返しファイルの内容は <code class="notranslate" translate="no">url</code> にあります。
  61. 次にファイルを解析するコードが必要です。</p>
  62. <pre class="prettyprint showlinemods notranslate lang-js" translate="no">function parseData(text) {
  63. const data = [];
  64. const settings = {data};
  65. let max;
  66. let min;
  67. // split into lines
  68. text.split('\n').forEach((line) =&gt; {
  69. // split the line by whitespace
  70. const parts = line.trim().split(/\s+/);
  71. if (parts.length === 2) {
  72. // only 2 parts, must be a key/value pair
  73. settings[parts[0]] = parseFloat(parts[1]);
  74. } else if (parts.length &gt; 2) {
  75. // more than 2 parts, must be data
  76. const values = parts.map((v) =&gt; {
  77. const value = parseFloat(v);
  78. if (value === settings.NODATA_value) {
  79. return undefined;
  80. }
  81. max = Math.max(max === undefined ? value : max, value);
  82. min = Math.min(min === undefined ? value : min, value);
  83. return value;
  84. });
  85. data.push(values);
  86. }
  87. });
  88. return Object.assign(settings, {min, max});
  89. }
  90. </pre>
  91. <p>上記のコードはファイルから全てのキーと値のペアを持つオブジェクトを返します。また<code class="notranslate" translate="no">data</code> プロパティには全てのデータを1つの大きな配列にまとめて、データに含まれる <code class="notranslate" translate="no">min</code> と <code class="notranslate" translate="no">max</code> の値を返します。</p>
  92. <p>次にデータの描画コードが必要です。</p>
  93. <pre class="prettyprint showlinemods notranslate lang-js" translate="no">function drawData(file) {
  94. const {min, max, data} = file;
  95. const range = max - min;
  96. const ctx = document.querySelector('canvas').getContext('2d');
  97. // make the canvas the same size as the data
  98. ctx.canvas.width = ncols;
  99. ctx.canvas.height = nrows;
  100. // but display it double size so it's not too small
  101. ctx.canvas.style.width = px(ncols * 2);
  102. ctx.canvas.style.height = px(nrows * 2);
  103. // fill the canvas to dark gray
  104. ctx.fillStyle = '#444';
  105. ctx.fillRect(0, 0, ctx.canvas.width, ctx.canvas.height);
  106. // draw each data point
  107. data.forEach((row, latNdx) =&gt; {
  108. row.forEach((value, lonNdx) =&gt; {
  109. if (value === undefined) {
  110. return;
  111. }
  112. const amount = (value - min) / range;
  113. const hue = 1;
  114. const saturation = 1;
  115. const lightness = amount;
  116. ctx.fillStyle = hsl(hue, saturation, lightness);
  117. ctx.fillRect(lonNdx, latNdx, 1, 1);
  118. });
  119. });
  120. }
  121. function px(v) {
  122. return `${v | 0}px`;
  123. }
  124. function hsl(h, s, l) {
  125. return `hsl(${h * 360 | 0},${s * 100 | 0}%,${l * 100 | 0}%)`;
  126. }
  127. </pre>
  128. <p>最後にすべてを統合します。</p>
  129. <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')
  130. .then(parseData)
  131. .then(drawData);
  132. </pre>
  133. <p>そして、以下のような結果が得られました。</p>
  134. <p></p><div translate="no" class="threejs_example_container notranslate">
  135. <div><iframe class="threejs_example notranslate" translate="no" style=" " src="/manual/examples/resources/editor.html?url=/manual/examples/gpw-data-viewer.html"></iframe></div>
  136. <a class="threejs_center" href="/manual/examples/gpw-data-viewer.html" target="_blank">ここをクリックして別のウィンドウで開きます</a>
  137. </div>
  138. <p></p>
  139. <p>どうやら上手くいったようです。</p>
  140. <p>これを3Dでやってみましょう。
  141. <a href="rendering-on-demand.html">要求されたレンダリング</a>のコードから始めてファイル内のデータごとに1つのボックスを作ります。</p>
  142. <p>まずは世界地図テクスチャで簡単な球体を作ってみましょう。テクスチャはこんな感じです。</p>
  143. <div class="threejs_center"><img src="../examples/resources/images/world.jpg" style="width: 600px"></div>
  144. <p>テクスチャをセットするコードです。</p>
  145. <pre class="prettyprint showlinemods notranslate lang-js" translate="no">{
  146. const loader = new THREE.TextureLoader();
  147. const texture = loader.load('resources/images/world.jpg', render);
  148. const geometry = new THREE.SphereGeometry(1, 64, 32);
  149. const material = new THREE.MeshBasicMaterial({map: texture});
  150. scene.add(new THREE.Mesh(geometry, material));
  151. }
  152. </pre>
  153. <p>テクスチャ読込後に <code class="notranslate" translate="no">render</code> を呼び出している部分に注目して下さい。
  154. renderが必要なのは連続的なレンダリングでなく、<a href="rendering-on-demand.html">要求されたレンダリング</a>なのでテクスチャ読込後に一度レンダリングする必要があるからです。</p>
  155. <p>次に上記のデータポイントごとにドット描画するコードをデータポイントごとにボックスを作成するコードに変更する必要があります。</p>
  156. <pre class="prettyprint showlinemods notranslate lang-js" translate="no">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) =&gt; {
  180. row.forEach((value, lonNdx) =&gt; {
  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. </pre>
  204. <p>2Dドットの描画コードからほとんどの部分が単純明快なものになっています。</p>
  205. <p>1つのボックスを作り、ボックスの中心が正のZから離れるように調整します。これをしないと中心からのスケールになってしまうため、原点から離れるようになってほしいからです。</p>
  206. <div class="spread">
  207. <div>
  208. <div data-diagram="scaleCenter" style="height: 250px"></div>
  209. <div class="code">default</div>
  210. </div>
  211. <div>
  212. <div data-diagram="scalePositiveZ" style="height: 250px"></div>
  213. <div class="code">adjusted</div>
  214. </div>
  215. </div>
  216. <p><a href="scenegraph.html">シーングラフ</a>で説明したように、多くの <a href="/docs/#api/ja/core/Object3D"><code class="notranslate" translate="no">THREE.Object3D</code></a> オブジェクトでボックスを親にして解決できますが、シーングラフにノードを追加すればするほど遅くなってしまいます。</p>
  217. <p>また <code class="notranslate" translate="no">lonHelper</code>、<code class="notranslate" translate="no">latHelper</code>、<code class="notranslate" translate="no">positionHelper</code>という小さなノード階層を設定します。
  218. これらのオブジェクトを使用し、ボックスを配置する球体の周りの位置を計算します。</p>
  219. <div class="spread">
  220. <div data-diagram="lonLatPos" style="width: 600px; height: 400px;"></div>
  221. </div>
  222. <p>上記の<span style="color: green;">green bar</span>は <code class="notranslate" translate="no">lonHelper</code> と <code class="notranslate" translate="no">longHelper</code> を表し、赤道上の経度方向に回転させるために使用します。
  223. <span style="color: blue;">blue bar</span> は <code class="notranslate" translate="no">latHelper</code> を表し、赤道上や赤道下の緯度を回転させるために使用します。
  224. <span style="color: red;">red sphere</span>は <code class="notranslate" translate="no">positionHelper</code> が提供するオフセットを表します。</p>
  225. <p>地球儀上の位置の計算を手動で行う事もできますが、ほとんどの計算をライブラリ自体に任せてしまうので処理をする必要がありません。</p>
  226. <p>各データポイントに対して <a href="/docs/#api/ja/materials/MeshBasicMaterial"><code class="notranslate" translate="no">MeshBasicMaterial</code></a> と <a href="/docs/#api/ja/objects/Mesh"><code class="notranslate" translate="no">Mesh</code></a> を作成し、<code class="notranslate" translate="no">positionHelper</code> のワールド座標を求めてそれを新しい <a href="/docs/#api/ja/objects/Mesh"><code class="notranslate" translate="no">Mesh</code></a> に適用します。
  227. 最後にメッシュを新しい位置で拡大縮小します。</p>
  228. <p>上記のように新しいボックスを作成する度に <code class="notranslate" translate="no">latHelper</code>、<code class="notranslate" translate="no">lonHelper</code>、<code class="notranslate" translate="no">positionHelper</code> を作成できましたが、それではさらに時間がかかります。</p>
  229. <p>これから作るボックスは360 × 145まであります。最大で52000個のボックスです。
  230. いくつかのデータポイントが "NO_DATA "とマークされているので、実際に作成するボックスの数は約19000個です。
  231. 1ボックスごとに3つのヘルパーオブジェクトを追加した場合、シーングラフのノードが80000個近くになり、THREE.jsはその位置を計算しなければなりません。
  232. ヘルパーの1つのセットを使用して単にメッシュを使用する事で約60000回の操作を削減できます。</p>
  233. <p>また <code class="notranslate" translate="no">lonFudge</code> と <code class="notranslate" translate="no">latFudge</code> には注意点があります。<code class="notranslate" translate="no">lonFudge</code> はπ/2で1/4回転です。
  234. これは理にかなっています。テクスチャやテクスチャ座標が地球の周りの異なるオフセットから始まる事を意味しているだけです。
  235. 一方、<code class="notranslate" translate="no">latFudge</code>についてはなぜπ * -0.135にする必要があるのか私にはわかりません。</p>
  236. <p>最後に行う必要があるのはローダーの呼出です。</p>
  237. <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')
  238. .then(parseData)
  239. - .then(drawData)
  240. + .then(addBoxes)
  241. + .then(render);
  242. </pre><p>データ読込と解析が終わったら、少なくとも一度は<a href="rendering-on-demand.html">要求されたレンダリング</a>をする必要があります。</p>
  243. <p></p><div translate="no" class="threejs_example_container notranslate">
  244. <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>
  245. <a class="threejs_center" href="/manual/examples/lots-of-objects-slow.html" target="_blank">ここをクリックして別のウィンドウで開きます</a>
  246. </div>
  247. <p></p>
  248. <p>上記のサンプルをドラッグして回転させようとすると遅い事に気づくでしょう。</p>
  249. <p><a href="debugging-javascript.html">devtoolsを開いて</a>FPS meterをオンにする事でFPSを確認できます。</p>
  250. <div class="threejs_center"><img src="../resources/images/bring-up-fps-meter.gif"></div>
  251. <p>私のマシンでは20fps以下のFPSが表示されています。</p>
  252. <div class="threejs_center"><img src="../resources/images/fps-meter.gif"></div>
  253. <p>FPSの遅延はあまり好ましくなく、多くの人々がさらにFPSが遅くなるマシンを持っているのではないでしょうか。最適化を検討した方がいいですね。</p>
  254. <p>このFPS遅延の問題解決では、全てのボックスを1つのジオメトリに統合する事ができます。
  255. 現在は19000個前後のボックスを描画してます。1つのジオメトリに統合する事で18999個の操作を削除する事ができます。</p>
  256. <p>以下はボックスを1つのジオメトリに統合する新しいコードです。</p>
  257. <pre class="prettyprint showlinemods notranslate lang-js" translate="no">function addBoxes(file) {
  258. const {min, max, data} = file;
  259. const range = max - min;
  260. - // make one box geometry
  261. - const boxWidth = 1;
  262. - const boxHeight = 1;
  263. - const boxDepth = 1;
  264. - const geometry = new THREE.BoxGeometry(boxWidth, boxHeight, boxDepth);
  265. - // make it so it scales away from the positive Z axis
  266. - geometry.applyMatrix4(new THREE.Matrix4().makeTranslation(0, 0, 0.5));
  267. // these helpers will make it easy to position the boxes
  268. // We can rotate the lon helper on its Y axis to the longitude
  269. const lonHelper = new THREE.Object3D();
  270. scene.add(lonHelper);
  271. // We rotate the latHelper on its X axis to the latitude
  272. const latHelper = new THREE.Object3D();
  273. lonHelper.add(latHelper);
  274. // The position helper moves the object to the edge of the sphere
  275. const positionHelper = new THREE.Object3D();
  276. positionHelper.position.z = 1;
  277. latHelper.add(positionHelper);
  278. + // Used to move the center of the box so it scales from the position Z axis
  279. + const originHelper = new THREE.Object3D();
  280. + originHelper.position.z = 0.5;
  281. + positionHelper.add(originHelper);
  282. const lonFudge = Math.PI * .5;
  283. const latFudge = Math.PI * -0.135;
  284. + const geometries = [];
  285. data.forEach((row, latNdx) =&gt; {
  286. row.forEach((value, lonNdx) =&gt; {
  287. if (value === undefined) {
  288. return;
  289. }
  290. const amount = (value - min) / range;
  291. - const material = new THREE.MeshBasicMaterial();
  292. - const hue = THREE.MathUtils.lerp(0.7, 0.3, amount);
  293. - const saturation = 1;
  294. - const lightness = THREE.MathUtils.lerp(0.1, 1.0, amount);
  295. - material.color.setHSL(hue, saturation, lightness);
  296. - const mesh = new THREE.Mesh(geometry, material);
  297. - scene.add(mesh);
  298. + const boxWidth = 1;
  299. + const boxHeight = 1;
  300. + const boxDepth = 1;
  301. + const geometry = new THREE.BoxGeometry(boxWidth, boxHeight, boxDepth);
  302. // adjust the helpers to point to the latitude and longitude
  303. lonHelper.rotation.y = THREE.MathUtils.degToRad(lonNdx + file.xllcorner) + lonFudge;
  304. latHelper.rotation.x = THREE.MathUtils.degToRad(latNdx + file.yllcorner) + latFudge;
  305. - // use the world matrix of the position helper to
  306. - // position this mesh.
  307. - positionHelper.updateWorldMatrix(true, false);
  308. - mesh.applyMatrix4(positionHelper.matrixWorld);
  309. -
  310. - mesh.scale.set(0.005, 0.005, THREE.MathUtils.lerp(0.01, 0.5, amount));
  311. + // use the world matrix of the origin helper to
  312. + // position this geometry
  313. + positionHelper.scale.set(0.005, 0.005, THREE.MathUtils.lerp(0.01, 0.5, amount));
  314. + originHelper.updateWorldMatrix(true, false);
  315. + geometry.applyMatrix4(originHelper.matrixWorld);
  316. +
  317. + geometries.push(geometry);
  318. });
  319. });
  320. + const mergedGeometry = BufferGeometryUtils.mergeBufferGeometries(
  321. + geometries, false);
  322. + const material = new THREE.MeshBasicMaterial({color:'red'});
  323. + const mesh = new THREE.Mesh(mergedGeometry, material);
  324. + scene.add(mesh);
  325. }
  326. </pre>
  327. <p>上記ではボックスジオメトリの中心点を変更していたコードを削除し、代わりに <code class="notranslate" translate="no">originHelper</code> を追加しています。
  328. 前は同じジオメトリを19000回も使っていました。
  329. 今回は1つ1つのジオメトリを新しく作成し、各ボックスジオメトリの頂点を移動するために <code class="notranslate" translate="no">applyMatrix</code> を使用するので、2回ではなく1回にした方が良いかもしれません。</p>
  330. <p>最後に全てのジオメトリの配列を <code class="notranslate" translate="no">BufferGeometryUtils.mergeBufferGeometries</code> に渡します。
  331. また <code class="notranslate" translate="no">BufferGeometryUtils</code> も含める必要があります。</p>
  332. <pre class="prettyprint showlinemods notranslate lang-js" translate="no">import * as BufferGeometryUtils from '/examples/jsm/utils/BufferGeometryUtils.js';
  333. </pre>
  334. <p>少なくとも私のマシンでは毎秒60フレームになりました。</p>
  335. <p></p><div translate="no" class="threejs_example_container notranslate">
  336. <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>
  337. <a class="threejs_center" href="/manual/examples/lots-of-objects-merged.html" target="_blank">ここをクリックして別のウィンドウで開きます</a>
  338. </div>
  339. <p></p>
  340. <p>これで上手くいったのですが、以前はそれぞれのボックスに異なる色がありましたが、1つのメッシュなので1つのマテリアルとなり1つの色だけになります。
  341. これは頂点カラーを使い修正できます。</p>
  342. <p>頂点カラーは頂点ごとに色を追加します。各ボックスの各頂点の全ての色を特定の色に設定する事で、全てのボックスが異なる色を持つようになります。</p>
  343. <pre class="prettyprint showlinemods notranslate lang-js" translate="no">+const color = new THREE.Color();
  344. const lonFudge = Math.PI * .5;
  345. const latFudge = Math.PI * -0.135;
  346. const geometries = [];
  347. data.forEach((row, latNdx) =&gt; {
  348. row.forEach((value, lonNdx) =&gt; {
  349. if (value === undefined) {
  350. return;
  351. }
  352. const amount = (value - min) / range;
  353. const boxWidth = 1;
  354. const boxHeight = 1;
  355. const boxDepth = 1;
  356. const geometry = new THREE.BoxGeometry(boxWidth, boxHeight, boxDepth);
  357. // adjust the helpers to point to the latitude and longitude
  358. lonHelper.rotation.y = THREE.MathUtils.degToRad(lonNdx + file.xllcorner) + lonFudge;
  359. latHelper.rotation.x = THREE.MathUtils.degToRad(latNdx + file.yllcorner) + latFudge;
  360. // use the world matrix of the origin helper to
  361. // position this geometry
  362. positionHelper.scale.set(0.005, 0.005, THREE.MathUtils.lerp(0.01, 0.5, amount));
  363. originHelper.updateWorldMatrix(true, false);
  364. geometry.applyMatrix4(originHelper.matrixWorld);
  365. + // compute a color
  366. + const hue = THREE.MathUtils.lerp(0.7, 0.3, amount);
  367. + const saturation = 1;
  368. + const lightness = THREE.MathUtils.lerp(0.4, 1.0, amount);
  369. + color.setHSL(hue, saturation, lightness);
  370. + // get the colors as an array of values from 0 to 255
  371. + const rgb = color.toArray().map(v =&gt; v * 255);
  372. +
  373. + // make an array to store colors for each vertex
  374. + const numVerts = geometry.getAttribute('position').count;
  375. + const itemSize = 3; // r, g, b
  376. + const colors = new Uint8Array(itemSize * numVerts);
  377. +
  378. + // copy the color into the colors array for each vertex
  379. + colors.forEach((v, ndx) =&gt; {
  380. + colors[ndx] = rgb[ndx % 3];
  381. + });
  382. +
  383. + const normalized = true;
  384. + const colorAttrib = new THREE.BufferAttribute(colors, itemSize, normalized);
  385. + geometry.setAttribute('color', colorAttrib);
  386. geometries.push(geometry);
  387. });
  388. });
  389. </pre>
  390. <p>上記のコードではジオメトリから <code class="notranslate" translate="no">position</code> を取得して必要な頂点の数を調べています。
  391. 次に色を入れるための変数を <code class="notranslate" translate="no">Uint8Array</code> で作成します。その後に <code class="notranslate" translate="no">geometry.setAttribute</code> を呼び出して属性として追加します。</p>
  392. <p>最後に頂点カラーを扱うようにthree.jsで指定する必要があります。</p>
  393. <pre class="prettyprint showlinemods notranslate lang-js" translate="no">const mergedGeometry = BufferGeometryUtils.mergeBufferGeometries(
  394. geometries, false);
  395. -const material = new THREE.MeshBasicMaterial({color:'red'});
  396. +const material = new THREE.MeshBasicMaterial({
  397. + vertexColors: true,
  398. +});
  399. const mesh = new THREE.Mesh(mergedGeometry, material);
  400. scene.add(mesh);
  401. </pre>
  402. <p>これで色を取り戻す事ができました。</p>
  403. <p></p><div translate="no" class="threejs_example_container notranslate">
  404. <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>
  405. <a class="threejs_center" href="/manual/examples/lots-of-objects-merged-vertexcolors.html" target="_blank">ここをクリックして別のウィンドウで開きます</a>
  406. </div>
  407. <p></p>
  408. <p>ジオメトリのマージは一般的な最適化手法です。
  409. 例えば100本の木を1つのジオメトリに統合したり、個々の岩の山を1つの岩のジオメトリに統合したり、個々の杭から1つの柵メッシュに統合したりする事ができます。
  410. 別の例としてマインクラフトではそれぞれのキューブを個別に描画するのではなく、マージされたキューブのグループを作成したり描画されない面は選択的に削除したりします。</p>
  411. <p>全てを1つのメッシュにする問題点としては、以前は分離されていた部分を移動する事が容易ではなくなった事です。
  412. ユースケースに応じて創造的なソリューションがあります。
  413. 1つは<a href="optimize-lots-of-objects-animated.html">別の記事</a>で紹介します。</p>
  414. <p><canvas id="c"></canvas></p>
  415. <script type="module" src="../resources/threejs-lots-of-objects.js"></script>
  416. </div>
  417. </div>
  418. </div>
  419. <script src="/manual/resources/prettify.js"></script>
  420. <script src="/manual/resources/lesson.js"></script>
  421. </body></html>