optimize-lots-of-objects.html 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437
  1. <!DOCTYPE html><html lang="ko"><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. <link rel="stylesheet" href="/manual/ko/lang.css">
  14. </head>
  15. <body>
  16. <div class="container">
  17. <div class="lesson-title">
  18. <h1>다중 요소 렌더링 최적화하기</h1>
  19. </div>
  20. <div class="lesson">
  21. <div class="lesson-main">
  22. <p>※ 이 글은 Three.js의 튜토리얼 시리즈로서,
  23. 먼저 <a href="fundamentals.html">Three.js의 기본 구조에 관한 글</a>을
  24. 읽고 오길 권장합니다.</p>
  25. <p>Three.js에서 요소를 최적화하는 방법은 아주 다양합니다. 가장 많이 언급되는 방법은 <em>geometry를 합치는 것</em>이죠. Three.js는 사용자가 <a href="/docs/#api/ko/objects/Mesh"><code class="notranslate" translate="no">Mesh</code></a>를 하나 만들 때마다 매번 시스템에 하나 이상의 렌더링 요청을 보냅니다. 결과물이 완벽히 같더라도 mesh를 1개를 렌더링할 때보다 2개를 렌더링할 때 <a href="https://ko.wikipedia.org/wiki/%EC%98%A4%EB%B2%84%ED%97%A4%EB%93%9C">오버헤드(overhead)</a>가 더 많이 발생한다는 이야기죠. 그러니 이 mesh를 하나로 합친다면 오버헤드를 줄일 수 있습니다.</p>
  26. <p>간단한 예제를 통해 이 방법이 어떤 경우 적합한지 알아보도록 하겠습니다. <a href="https://globe.chromeexperiments.com/">WebGL 지구본</a>을 베껴 직접 구현해보겠습니다.</p>
  27. <p>먼저 데이터를 작성합니다. WebGL 지구본 개발진은 <a href="http://sedac.ciesin.columbia.edu/gpw/">SEDAC</a>에서 데이터를 가져왔다고 합니다. 사이트를 뒤져보니 <a href="https://beta.sedac.ciesin.columbia.edu/data/set/gpw-v4-basic-demographic-characteristics-rev10">그리드 형태의 인구 통계 데이터</a>가 있네요. resolution 값을 60 minute으로 설정해 데이터를 다운로드합니다.</p>
  28. <p>받은 데이터는 아래와 같습니다.</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>키/값 쌍 데이터가 몇 줄 있고 나머지는 격자점(grid point) 데이터네요. 데이터의 한 줄은 각 좌표에 대한 데이터입니다.</p>
  53. <p>이해를 돕기 위해 데이터를 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">url</code>의 파일 내용을 반환하는 <code class="notranslate" translate="no">Promise</code>를 반환합니다.</p>
  61. <p>※참고: <a href="https://developer.mozilla.org/ko/docs/Web/API/Fetch_API">fetch API</a>. 역주.</p>
  62. <p>다음으로 텍스트 데이터를 파싱하는 함수를 작성합니다.</p>
  63. <pre class="prettyprint showlinemods notranslate lang-js" translate="no">function parseData(text) {
  64. const data = [];
  65. const settings = { data };
  66. let max;
  67. let min;
  68. // 각 줄을 쪼갭니다.
  69. text.split('\n').forEach((line) =&gt; {
  70. // 해당 줄을 공백을 기준으로 쪼갭니다.
  71. const parts = line.trim().split(/\s+/);
  72. if (parts.length === 2) {
  73. // 2개로 나눠졌다면 키/값 쌍 데이터입니다.
  74. settings[parts[0]] = parseFloat(parts[1]);
  75. } else if (parts.length &gt; 2) {
  76. // 2개보다 많다면 좌표 데이터입니다.
  77. const values = parts.map((v) =&gt; {
  78. const value = parseFloat(v);
  79. if (value === settings.NODATA_value) {
  80. return undefined;
  81. }
  82. max = Math.max(max === undefined ? value : max, value);
  83. min = Math.min(min === undefined ? value : min, value);
  84. return value;
  85. });
  86. data.push(values);
  87. }
  88. });
  89. return Object.assign(settings, { min, max });
  90. }
  91. </pre>
  92. <p>위 함수는 데이터 파일의 키/값 쌍, 좌표 데이터를 하나의 배열 만든 <code class="notranslate" translate="no">data</code> 속성, 그리고 좌표 데이터를 기반으로 한 <code class="notranslate" translate="no">min</code>, <code class="notranslate" translate="no">max</code> 속성을 가진 객체를 반환합니다.</p>
  93. <p>그리고 데이터를 렌더링하는 코드를 작성합니다.</p>
  94. <pre class="prettyprint showlinemods notranslate lang-js" translate="no">function drawData(file) {
  95. const { min, max, data } = file;
  96. const range = max - min;
  97. const ctx = document.querySelector('canvas').getContext('2d');
  98. // 데이터와 같은 크기로 캔버스 해상도를 맞춥니다.
  99. ctx.canvas.width = ncols;
  100. ctx.canvas.height = nrows;
  101. // 캔버스 요소의 크기를 두 배로 지정해 너무 작게 보이지 않도록 합니다.
  102. ctx.canvas.style.width = px(ncols * 2);
  103. ctx.canvas.style.height = px(nrows * 2);
  104. // 배경을 짙은 회색으로 채웁니다.
  105. ctx.fillStyle = '#444';
  106. ctx.fillRect(0, 0, ctx.canvas.width, ctx.canvas.height);
  107. // 각 좌표에 점을 그립니다.
  108. data.forEach((row, latNdx) =&gt; {
  109. row.forEach((value, lonNdx) =&gt; {
  110. if (value === undefined) {
  111. return;
  112. }
  113. const amount = (value - min) / range;
  114. const hue = 1;
  115. const saturation = 1;
  116. const lightness = amount;
  117. ctx.fillStyle = hsl(hue, saturation, lightness);
  118. ctx.fillRect(lonNdx, latNdx, 1, 1);
  119. });
  120. });
  121. }
  122. function px(v) {
  123. return `${ v | 0 }px`;
  124. }
  125. function hsl(h, s, l) {
  126. return `hsl(${ h * 360 | 0 },${ s * 100 | 0 }%,${ l * 100 | 0 }%)`;
  127. }
  128. </pre>
  129. <p>작성한 함수를 순서대로 실행하면 끝입니다.</p>
  130. <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')
  131. .then(parseData)
  132. .then(drawData);
  133. </pre>
  134. <p>결과를 볼까요?</p>
  135. <p></p><div translate="no" class="threejs_example_container notranslate">
  136. <div><iframe class="threejs_example notranslate" translate="no" style=" " src="/manual/examples/resources/editor.html?url=/manual/examples/gpw-data-viewer.html"></iframe></div>
  137. <a class="threejs_center" href="/manual/examples/gpw-data-viewer.html" target="_blank">새 탭에서 보기</a>
  138. </div>
  139. <p></p>
  140. <p>데이터가 잘 렌더링된 것 같네요.</p>
  141. <p>이제 이걸 3D로 만들어봅시다. <a href="rendering-on-demand.html">불필요한 렌더링 제거하기</a>에서 썼던 예제를 가져와 각 데이터마다 육면체를 하나씩 만들 겁니다.</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> 함수를 호출하게 했습니다. 화면을 반복해서 렌더링하지 않고 <a href="rendering-on-demand.html">필요할 때만 렌더링</a>하므로, 텍스처를 불러온 뒤 다시 한 번 렌더링해야 합니다.</p>
  154. <p>다음으로 데이터를 하나의 점으로 표시하는 대신 좌표 데이터마다 육면체를 하나씩 생성합니다.</p>
  155. <pre class="prettyprint showlinemods notranslate lang-js" translate="no">function addBoxes(file) {
  156. const { min, max, data } = file;
  157. const range = max - min;
  158. // 육면체 geometry를 만듭니다.
  159. const boxWidth = 1;
  160. const boxHeight = 1;
  161. const boxDepth = 1;
  162. const geometry = new THREE.BoxGeometry(boxWidth, boxHeight, boxDepth);
  163. // 중심이 아닌 양의 z축 방향으로 커지게끔 만듭니다.
  164. geometry.applyMatrix4(new THREE.Matrix4().makeTranslation(0, 0, 0.5));
  165. // 아래 헬퍼 Object3D는 육면체들의 위치 변화를 간단하게 만들어줍니다.
  166. // lonHelper를 Y축으로 돌려 경도(longitude)를 맞출 수 있습니다.
  167. const lonHelper = new THREE.Object3D();
  168. scene.add(lonHelper);
  169. // latHelper를 X축으로 돌려 위도(latitude)를 맞출 수 있습니다.
  170. const latHelper = new THREE.Object3D();
  171. lonHelper.add(latHelper);
  172. // positionHelper는 다른 요소의 기준축을 구체의 끝에 맞추는 역할을 합니다.
  173. const positionHelper = new THREE.Object3D();
  174. positionHelper.position.z = 1;
  175. latHelper.add(positionHelper);
  176. const lonFudge = Math.PI * .5;
  177. const latFudge = Math.PI * -0.135;
  178. data.forEach((row, latNdx) =&gt; {
  179. row.forEach((value, lonNdx) =&gt; {
  180. if (value === undefined) {
  181. return;
  182. }
  183. const amount = (value - min) / range;
  184. const material = new THREE.MeshBasicMaterial();
  185. const hue = THREE.MathUtils.lerp(0.7, 0.3, amount);
  186. const saturation = 1;
  187. const lightness = THREE.MathUtils.lerp(0.1, 1.0, amount);
  188. material.color.setHSL(hue, saturation, lightness);
  189. const mesh = new THREE.Mesh(geometry, material);
  190. scene.add(mesh);
  191. // 헬퍼들을 특정 위도와 경도로 이동시킵니다.
  192. lonHelper.rotation.y = THREE.MathUtils.degToRad(lonNdx + file.xllcorner) + lonFudge;
  193. latHelper.rotation.x = THREE.MathUtils.degToRad(latNdx + file.yllcorner) + latFudge;
  194. // positionHelper의 위치를 해당 mesh의 위치로 지정합니다.
  195. positionHelper.updateWorldMatrix(true, false);
  196. mesh.applyMatrix4(positionHelper.matrixWorld);
  197. mesh.scale.set(0.005, 0.005, THREE.MathUtils.lerp(0.01, 0.5, amount));
  198. });
  199. });
  200. }
  201. </pre>
  202. <p>위 코드는 아까 만들었던 테스트 코드의 구조를 그대로 사용한 것입니다.</p>
  203. <p>각 육면체를 양의 Z축으로 커지게 만든 건 지구본 위에 그래프가 올라와야 하기 때문입니다. 이 설정이 없다면 그래프가 지구본 안쪽으로 파고들어 가겠죠.</p>
  204. <div class="spread">
  205. <div>
  206. <div data-diagram="scaleCenter" style="height: 250px"></div>
  207. <div class="code">기본값</div>
  208. </div>
  209. <div>
  210. <div data-diagram="scalePositiveZ" style="height: 250px"></div>
  211. <div class="code">Z축을 조정한 결과</div>
  212. </div>
  213. </div>
  214. <p><a href="scenegraph.html">씬 그래프에 관한 글</a>에서 배웠듯 육면체를 다른 <a href="/docs/#api/ko/core/Object3D"><code class="notranslate" translate="no">THREE.Object3D</code></a>의 자식으로 두는 것도 한 가지 해결 방법이지만, 씬 그래프 요소가 많아지만 그만큼 성능이 떨어집니다.</p>
  215. <p><code class="notranslate" translate="no">lonHelper</code>, <code class="notranslate" translate="no">latHelper</code>, <code class="notranslate" translate="no">positionHelper</code>를 계층 구조로 만든 건 구체 주위에 육면체를 배치할 좌표를 찾기 위해서입니다.</p>
  216. <div class="spread">
  217. <div data-diagram="lonLatPos" style="width: 600px; height: 400px;"></div>
  218. </div>
  219. <p>위 예제의 <span style="color:green;">초록색 막대</span>는 <code class="notranslate" translate="no">lonHelper</code>를 상징합니다. 자전축을 중심으로 경도(longitude)를 찾는 역할을 하죠. <span style="color:blue">파란색 막대</span>는 <code class="notranslate" translate="no">latHelper</code>입니다. <code class="notranslate" translate="no">latHelper</code>는 적도 위 아래로 위도(latitude)를 찾는 역할을 합니다. <span style="color:red;">빨간 구체</span>는 <code class="notranslate" translate="no">positionHelper</code>로, 육면체의 좌표값을 나타냅니다.</p>
  220. <p>물론 좌표를 계산할 때 수학적으로 접근할 수도 있지만, 이렇게 라이브러리가 대신 계산하도록 하면 복잡하게 머리를 쥐어짜야할 필요가 없습니다.</p>
  221. <p>위 코드에서는 각 데이터 좌표마다 <a href="/docs/#api/ko/materials/MeshBasicMaterial"><code class="notranslate" translate="no">MeshBasicMaterial</code></a>와 <a href="/docs/#api/ko/objects/Mesh"><code class="notranslate" translate="no">Mesh</code></a>를 생성했습니다. 그리고 <code class="notranslate" translate="no">positionHelper</code>의 전역 좌표를 구해 <a href="/docs/#api/ko/objects/Mesh"><code class="notranslate" translate="no">Mesh</code></a>에 적용하고, 데이터의 양만큼 이 mesh를 키웠죠.</p>
  222. <p>아까와 마찬가지로 각 데이터마다 <code class="notranslate" translate="no">lonHelper</code>, <code class="notranslate" translate="no">latHelper</code>, <code class="notranslate" translate="no">positionHelper</code>를 따로 생성할 수도 있지만, 그렇게 하면 성능이 훨씬 느려질 겁니다.</p>
  223. <p>이러면 육면체를 최대 360x145개, 거의 최대 52000개를 만드는 셈입니다. "NO_DATA"라고 표시된 곳도 있기에 그걸 제외하면 육면체의 개수는 대략 19000개가 될 겁니다. 그런데 여기에 각 육면체에 따로 3개씩 헬퍼를 생성한다면 Three.js는 거의 80000개의 씬 그래프 요소를 계산하게 되죠. 대신 헬퍼를 공통으로 사용하면 연산 요청을 약 60000번 정도 줄일 수 있습니다.</p>
  224. <p><code class="notranslate" translate="no">lonFudge</code>와 <code class="notranslate" translate="no">latFudge</code>에 대해 짧게 언급하겠습니다. <code class="notranslate" translate="no">lonFudge</code>는 π/2, 90도입니다. 이건 크게 신경쓸 게 없네요. 그냥 텍스처나 텍스처 좌표가 다른 각도에서 시작한다는 소리니까요. 하지만 <code class="notranslate" translate="no">latFudge</code>의 경우는 왜 π * -0.135가 필요한지 모르겠습니다. 그냥 좌표가 저 축을 기준으로 정렬되어 있습니다.</p>
  225. <p>이제 만든 함수를 호출합니다.</p>
  226. <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')
  227. .then(parseData)
  228. - .then(drawData)
  229. + .then(addBoxes)
  230. + .then(render);
  231. </pre><p><a href="rendering-on-demand.html">필요할 때만 렌더링 함수를 호출</a>하게 해놨으므로 지구본과 육면체들을 추가한 뒤 <code class="notranslate" translate="no">render</code> 함수를 직접 호출해야 합니다.</p>
  232. <p></p><div translate="no" class="threejs_example_container notranslate">
  233. <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>
  234. <a class="threejs_center" href="/manual/examples/lots-of-objects-slow.html" target="_blank">새 탭에서 보기</a>
  235. </div>
  236. <p></p>
  237. <p>위 예제를 드래그해 지구본을 돌려보면 뭔가 버벅임을 느낄 수 있을 겁니다.</p>
  238. <p><a href="debugging-javascript.html">개발자 도구를 열어</a> 브라우저의 FPS 미터를 켜면 프레임율을 확인할 수 있습니다.</p>
  239. <div class="threejs_center"><img src="../resources/images/bring-up-fps-meter.gif"></div>
  240. <p>제 환경에서는 평균 프레임이 20fps보다 낮네요.</p>
  241. <div class="threejs_center"><img src="../resources/images/fps-meter.gif"></div>
  242. <p>아마 더 안 좋은 컴퓨터에서는 이보다 더 심할 겁니다. 최적화할 방법을 찾아봐야겠네요.</p>
  243. <p>예제의 경우 모든 정육면체를 하나의 geometry로 합치는 방법을 적용할 수 있습니다. 현재 거의 육면체를 거의 19000개 정도 렌더링했는데, 이를 하나로 합치면 연산 요청을 18999회 정도 줄일 수 있습니다.</p>
  244. <pre class="prettyprint showlinemods notranslate lang-js" translate="no">function addBoxes(file) {
  245. const {min, max, data} = file;
  246. const range = max - min;
  247. - // 육면체 geometry를 만듭니다.
  248. - const boxWidth = 1;
  249. - const boxHeight = 1;
  250. - const boxDepth = 1;
  251. - const geometry = new THREE.BoxGeometry(boxWidth, boxHeight, boxDepth);
  252. - // 중심이 아닌 양의 z축 방향으로 커지게끔 만듭니다.
  253. - geometry.applyMatrix4(new THREE.Matrix4().makeTranslation(0, 0, 0.5));
  254. // 아래 헬퍼 Object3D는 육면체들의 위치 변화를 간단하게 만들어줍니다.
  255. // lonHelper를 Y축으로 돌려 경도(longitude)를 맞출 수 있습니다.
  256. const lonHelper = new THREE.Object3D();
  257. scene.add(lonHelper);
  258. // latHelper를 X축으로 돌려 위도(latitude)를 맞출 수 있습니다.
  259. const latHelper = new THREE.Object3D();
  260. lonHelper.add(latHelper);
  261. // positionHelper는 다른 요소의 기준축을 구체의 끝에 맞추는 역할을 합니다.
  262. const positionHelper = new THREE.Object3D();
  263. positionHelper.position.z = 1;
  264. latHelper.add(positionHelper);
  265. + // 육면체의 중심을 옮겨 양의 Z축 방향으로 커지게 합니다.
  266. + const originHelper = new THREE.Object3D();
  267. + originHelper.position.z = 0.5;
  268. + positionHelper.add(originHelper);
  269. const lonFudge = Math.PI * .5;
  270. const latFudge = Math.PI * -0.135;
  271. + const geometries = [];
  272. data.forEach((row, latNdx) =&gt; {
  273. row.forEach((value, lonNdx) =&gt; {
  274. if (value === undefined) {
  275. return;
  276. }
  277. const amount = (value - min) / range;
  278. - const material = new THREE.MeshBasicMaterial();
  279. - const hue = THREE.MathUtils.lerp(0.7, 0.3, amount);
  280. - const saturation = 1;
  281. - const lightness = THREE.MathUtils.lerp(0.1, 1.0, amount);
  282. - material.color.setHSL(hue, saturation, lightness);
  283. - const mesh = new THREE.Mesh(geometry, material);
  284. - scene.add(mesh);
  285. + const boxWidth = 1;
  286. + const boxHeight = 1;
  287. + const boxDepth = 1;
  288. + const geometry = new THREE.BoxGeometry(boxWidth, boxHeight, boxDepth);
  289. // 헬퍼들을 특정 위도와 경도로 이동시킵니다.
  290. lonHelper.rotation.y = THREE.MathUtils.degToRad(lonNdx + file.xllcorner) + lonFudge;
  291. latHelper.rotation.x = THREE.MathUtils.degToRad(latNdx + file.yllcorner) + latFudge;
  292. - // positionHelper의 위치를 해당 mesh의 위치로 지정합니다.
  293. - positionHelper.updateWorldMatrix(true, false);
  294. - mesh.applyMatrix4(positionHelper.matrixWorld);
  295. -
  296. - mesh.scale.set(0.005, 0.005, THREE.MathUtils.lerp(0.01, 0.5, amount));
  297. + // originHelper의 위치를 해당 geometry의 위치로 지정합니다.
  298. + positionHelper.scale.set(0.005, 0.005, THREE.MathUtils.lerp(0.01, 0.5, amount));
  299. + originHelper.updateWorldMatrix(true, false);
  300. + geometry.applyMatrix4(originHelper.matrixWorld);
  301. +
  302. + geometries.push(geometry);
  303. });
  304. });
  305. + // 생성한 geometry를 전부 합칩니다.
  306. + const mergedGeometry = BufferGeometryUtils.mergeBufferGeometries(
  307. + geometries, false);
  308. + const material = new THREE.MeshBasicMaterial({ color:'red' });
  309. + const mesh = new THREE.Mesh(mergedGeometry, material);
  310. + scene.add(mesh);
  311. }
  312. </pre>
  313. <p>위 코드에서는 육면체의 중심을 옮기는 대신 <code class="notranslate" translate="no">originHelper</code>를 새로 만들어 중심축을 옮겼습니다. 이전에는 같은 geometry를 19000번 재활용했지만, 이번에는 데이터마다 geometry를 새로 생성했죠. 또한 <code class="notranslate" translate="no">applyMatrix</code>를 이용해 육면체 자체의 정점을 이동시키므로 메서드를 두 번 쓰는 대신 한 번만 썼습니다.</p>
  314. <p>그리고 생성한 육면체를 전부 배열에 저장한 뒤 이 배열을 <code class="notranslate" translate="no">BufferGeometryUtils.mergeBufferGeometries</code>에 넘겨 하나의 geometry로 합쳤습니다.</p>
  315. <p>물론 <code class="notranslate" translate="no">BufferGeometryUtils</code>을 불러와야죠.</p>
  316. <pre class="prettyprint showlinemods notranslate lang-js" translate="no">import { BufferGeometryUtils } from '/examples/jsm/utils/BufferGeometryUtils.js';
  317. </pre>
  318. <p>이제 제 컴퓨터에서는 적어도 60 프레임 이상이 나오네요.</p>
  319. <p></p><div translate="no" class="threejs_example_container notranslate">
  320. <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>
  321. <a class="threejs_center" href="/manual/examples/lots-of-objects-merged.html" target="_blank">새 탭에서 보기</a>
  322. </div>
  323. <p></p>
  324. <p>성능 문제는 해결했지만 육면체가 하나의 mesh이기에 이전과 달리 육면체의 색이 전부 같습니다. 여기서 색을 따로 지정하려면? 여러 방법이 있겠지만 정점 색(vertex color)을 쓰는 방법이 제일 간단할 겁니다.</p>
  325. <p>정점 색은 정점마다 색을 지정합니다. 각 육면체의 각 정점을 다른 색으로 지정하면 육면체의 색을 다르게 지정할 수 있겠죠.</p>
  326. <pre class="prettyprint showlinemods notranslate lang-js" translate="no">+const color = new THREE.Color();
  327. const lonFudge = Math.PI * .5;
  328. const latFudge = Math.PI * -0.135;
  329. const geometries = [];
  330. data.forEach((row, latNdx) =&gt; {
  331. row.forEach((value, lonNdx) =&gt; {
  332. if (value === undefined) {
  333. return;
  334. }
  335. const amount = (value - min) / range;
  336. const boxWidth = 1;
  337. const boxHeight = 1;
  338. const boxDepth = 1;
  339. const geometry = new THREE.BoxGeometry(boxWidth, boxHeight, boxDepth);
  340. // 헬퍼들을 특정 위도와 경도로 이동시킵니다.
  341. lonHelper.rotation.y = THREE.MathUtils.degToRad(lonNdx + file.xllcorner) + lonFudge;
  342. latHelper.rotation.x = THREE.MathUtils.degToRad(latNdx + file.yllcorner) + latFudge;
  343. // originHelper의 위치를 해당 geometry의 위치로 지정합니다.
  344. positionHelper.scale.set(0.005, 0.005, THREE.MathUtils.lerp(0.01, 0.5, amount));
  345. originHelper.updateWorldMatrix(true, false);
  346. geometry.applyMatrix4(originHelper.matrixWorld);
  347. + // 색상값을 계산합니다.
  348. + const hue = THREE.MathUtils.lerp(0.7, 0.3, amount);
  349. + const saturation = 1;
  350. + const lightness = THREE.MathUtils.lerp(0.4, 1.0, amount);
  351. + color.setHSL(hue, saturation, lightness);
  352. + // RGB 색상값을 0부터 255까지의 배열로 변환합니다.
  353. + const rgb = color.toArray().map(v =&gt; v * 255);
  354. +
  355. + // 각 정점의 색을 배열로 저장합니다.
  356. + const numVerts = geometry.getAttribute('position').count;
  357. + const itemSize = 3; // r, g, b
  358. + const colors = new Uint8Array(itemSize * numVerts);
  359. +
  360. + // 색상값을 각 정점에 지정할 색상으로 변환합니다.
  361. + colors.forEach((v, ndx) =&gt; {
  362. + colors[ndx] = rgb[ndx % 3];
  363. + });
  364. +
  365. + const normalized = true;
  366. + const colorAttrib = new THREE.BufferAttribute(colors, itemSize, normalized);
  367. + geometry.setAttribute('color', colorAttrib);
  368. geometries.push(geometry);
  369. });
  370. });
  371. </pre>
  372. <p>추가한 코드에서는 먼저 geometry의 <code class="notranslate" translate="no">position</code> 속성을 가져와 정점의 개수를 파악했습니다. 그런 다음 색상을 지정하기 위해 <code class="notranslate" translate="no">Uint8Array</code>로 변환한 뒤, 이를 <code class="notranslate" translate="no">geometry.setAttribute</code> 메서드로 geometry의 <code class="notranslate" translate="no">color</code> 속성에 지정했죠.</p>
  373. <p>마지막으로 재질(material)이 정점 색상을 사용하도록 설정합니다.</p>
  374. <pre class="prettyprint showlinemods notranslate lang-js" translate="no">const mergedGeometry = BufferGeometryUtils.mergeBufferGeometries(
  375. geometries, false);
  376. -const material = new THREE.MeshBasicMaterial({color:'red'});
  377. +const material = new THREE.MeshBasicMaterial({
  378. + vertexColors: true,
  379. +});
  380. const mesh = new THREE.Mesh(mergedGeometry, material);
  381. scene.add(mesh);
  382. </pre>
  383. <p>이제 색이 다시 정상적으로 보입니다.</p>
  384. <p></p><div translate="no" class="threejs_example_container notranslate">
  385. <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>
  386. <a class="threejs_center" href="/manual/examples/lots-of-objects-merged-vertexcolors.html" target="_blank">새 탭에서 보기</a>
  387. </div>
  388. <p></p>
  389. <p>geometry를 합치는 건 꽤 자주 사용하는 최적화 기법입니다. 예를 들어 나무 100개를 하나의 geometry로 합치거나, 돌무더기를 하나의 돌 geometry로 합치거나, 울타리의 각 기둥을 하나의 mesh로 합치는 경우가 해당되죠. 마인크래프트의 경우도 모든 타일을 하나하나 다 렌더링하기보다 타일을 하나로 합쳐 보이지 않는 면은 제거하는 기법을 사용할 확률이 높습니다.</p>
  390. <p>하지만 요소를 하나의 mesh로 합쳐버리면 별도의 요소였던 특정 부분을 조작하기가 어렵습니다. 상황에 따라 좋은 방법도 다 다를 테죠. <a href="optimize-lots-of-objects-animated.html">다음 글</a>에서는 그 방법 중 하나를 살펴보겠습니다.</p>
  391. <p><canvas id="c"></canvas></p>
  392. <script type="module" src="../resources/threejs-lots-of-objects.js"></script>
  393. </div>
  394. </div>
  395. </div>
  396. <script src="/manual/resources/prettify.js"></script>
  397. <script src="/manual/resources/lesson.js"></script>
  398. </body></html>