1
0

optimize-lots-of-objects.html 27 KB

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