custom-buffergeometry.html 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386
  1. Title: Three.jsのカスタムバッファジオメトリ
  2. Description: カスタムバッファジオメトリを作る
  3. TOC: カスタムバッファジオメトリ
  4. `BufferGeometry`は全てのジオメトリを表現する方法です。
  5. BufferGeometryは`BufferAttribute`を使います。1つの`BufferAttribute`はジオメトリを作るための1種類のデータに対応しています。vertexの位置情報を格納するための`BufferAttribute`、color情報を格納するための`BufferAttribute`、normal情報を格納するための`BufferAttribute`がそれぞれあります。
  6. <div class="threejs_center"><img src="resources/threejs-attributes.svg" style="width: 700px"></div>
  7. 上の図では`position`, `normal`, `color`, `uv`それぞれのattribute情報を格納した`BufferAttribute`を表しています。これらは*並列な配列*です。*並列な配列*というのはN番目にあるデータはN番目のvertexに対応しており、それがattributeの数だけあるという意味です。図ではindex=4のattributeがハイライトされています。
  8. <div class="threejs_center"><img src="resources/cube-faces-vertex.svg" style="width: 500px"></div>
  9. 上の図のハイライトされたvertexには、このvertexに接する全ての面に異なるnormalが必要です。normalとはどの方向を向いているかの情報です。
  10. この図ではnormalは角の頂点の周りの矢印で示されており、その頂点に接する全ての面には異なる方向を指すnormalが必要です。
  11. 同様に面ごとに違うUVも必要です。
  12. UVはテクスチャのどの部分に頂点位置が対応しているか指定するテクスチャ座標です。
  13. 緑の面はFテクスチャの右上に対応するUV、青い面は左上に対応するUV、赤の面は左下に対応したUVが必要な事が分かります。
  14. 単一のvertexはこれらの情報の合成として表現されます。
  15. 頂点が異なる部分を必要とする場合、それは異なる頂点でなければなりません。
  16. 簡単な例として`BufferGeometry`を使って立方体を作ってみましょう。立方体を例にするのはvertexがfaceによって共有されているように見えて実は共有されていないからです。この例ではまずすべてのvertexの情報をリストアップして並列の配列に変換して`BufferAttribute`を作り、最後に`BufferGeometry`を作ります。
  17. 立方体に必要な情報をすべてリストアップします。`Geometry`では1つのvertexを複数のfaceで共有できましたが今回は共有できないことに注意してください。つまり1つの立方体を作るために36個のvertexが必要になります。1つの面につき2つの三角形、1つの三角形につき3つのvertex、これが6面あるので36個のvertexが必要になる計算です。
  18. ```js
  19. const vertices = [
  20. // front
  21. { pos: [-1, -1, 1], norm: [ 0, 0, 1], uv: [0, 0], },
  22. { pos: [ 1, -1, 1], norm: [ 0, 0, 1], uv: [1, 0], },
  23. { pos: [-1, 1, 1], norm: [ 0, 0, 1], uv: [0, 1], },
  24. { pos: [-1, 1, 1], norm: [ 0, 0, 1], uv: [0, 1], },
  25. { pos: [ 1, -1, 1], norm: [ 0, 0, 1], uv: [1, 0], },
  26. { pos: [ 1, 1, 1], norm: [ 0, 0, 1], uv: [1, 1], },
  27. // right
  28. { pos: [ 1, -1, 1], norm: [ 1, 0, 0], uv: [0, 0], },
  29. { pos: [ 1, -1, -1], norm: [ 1, 0, 0], uv: [1, 0], },
  30. { pos: [ 1, 1, 1], norm: [ 1, 0, 0], uv: [0, 1], },
  31. { pos: [ 1, 1, 1], norm: [ 1, 0, 0], uv: [0, 1], },
  32. { pos: [ 1, -1, -1], norm: [ 1, 0, 0], uv: [1, 0], },
  33. { pos: [ 1, 1, -1], norm: [ 1, 0, 0], uv: [1, 1], },
  34. // back
  35. { pos: [ 1, -1, -1], norm: [ 0, 0, -1], uv: [0, 0], },
  36. { pos: [-1, -1, -1], norm: [ 0, 0, -1], uv: [1, 0], },
  37. { pos: [ 1, 1, -1], norm: [ 0, 0, -1], uv: [0, 1], },
  38. { pos: [ 1, 1, -1], norm: [ 0, 0, -1], uv: [0, 1], },
  39. { pos: [-1, -1, -1], norm: [ 0, 0, -1], uv: [1, 0], },
  40. { pos: [-1, 1, -1], norm: [ 0, 0, -1], uv: [1, 1], },
  41. // left
  42. { pos: [-1, -1, -1], norm: [-1, 0, 0], uv: [0, 0], },
  43. { pos: [-1, -1, 1], norm: [-1, 0, 0], uv: [1, 0], },
  44. { pos: [-1, 1, -1], norm: [-1, 0, 0], uv: [0, 1], },
  45. { pos: [-1, 1, -1], norm: [-1, 0, 0], uv: [0, 1], },
  46. { pos: [-1, -1, 1], norm: [-1, 0, 0], uv: [1, 0], },
  47. { pos: [-1, 1, 1], norm: [-1, 0, 0], uv: [1, 1], },
  48. // top
  49. { pos: [ 1, 1, -1], norm: [ 0, 1, 0], uv: [0, 0], },
  50. { pos: [-1, 1, -1], norm: [ 0, 1, 0], uv: [1, 0], },
  51. { pos: [ 1, 1, 1], norm: [ 0, 1, 0], uv: [0, 1], },
  52. { pos: [ 1, 1, 1], norm: [ 0, 1, 0], uv: [0, 1], },
  53. { pos: [-1, 1, -1], norm: [ 0, 1, 0], uv: [1, 0], },
  54. { pos: [-1, 1, 1], norm: [ 0, 1, 0], uv: [1, 1], },
  55. // bottom
  56. { pos: [ 1, -1, 1], norm: [ 0, -1, 0], uv: [0, 0], },
  57. { pos: [-1, -1, 1], norm: [ 0, -1, 0], uv: [1, 0], },
  58. { pos: [ 1, -1, -1], norm: [ 0, -1, 0], uv: [0, 1], },
  59. { pos: [ 1, -1, -1], norm: [ 0, -1, 0], uv: [0, 1], },
  60. { pos: [-1, -1, 1], norm: [ 0, -1, 0], uv: [1, 0], },
  61. { pos: [-1, -1, -1], norm: [ 0, -1, 0], uv: [1, 1], },
  62. ];
  63. ```
  64. 次にこれを3つの並列な配列に変換します。
  65. (訳註:並列な配列*parallel arrays*とは例えば頂点を指定する配列と色を指定する配列があり1つの頂点をレンダリングするために2つの配列の同じインデックスの要素を指定するような使われ方をする配列のことです。次の例ではpositions, normals, uvsの3つの配列が並列の配列として使われています)
  66. ```js
  67. const positions = [];
  68. const normals = [];
  69. const uvs = [];
  70. for (const vertex of vertices) {
  71. positions.push(...vertex.pos);
  72. normals.push(...vertex.norm);
  73. uvs.push(...vertex.uv);
  74. }
  75. ```
  76. 最後にそれぞれの配列に対して`BufferAttribute`を作り`BufferGeometry`に指定します。
  77. ```js
  78. const geometry = new THREE.BufferGeometry();
  79. const positionNumComponents = 3;
  80. const normalNumComponents = 3;
  81. const uvNumComponents = 2;
  82. geometry.setAttribute(
  83. 'position',
  84. new THREE.BufferAttribute(new Float32Array(positions), positionNumComponents));
  85. geometry.setAttribute(
  86. 'normal',
  87. new THREE.BufferAttribute(new Float32Array(normals), normalNumComponents));
  88. geometry.setAttribute(
  89. 'uv',
  90. new THREE.BufferAttribute(new Float32Array(uvs), uvNumComponents));
  91. ```
  92. 名前の付け方に注意してください。three.jsで決められている名前以外を指定することはできません(カスタムシェーダーを使用する場合は別です)。`position`, `normal`, `uv`はthree.jsで決められている名前です。ここでは指定していませんが`color`も指定可能です。
  93. 上の例では`positions`, `normals`, `uvs`の3つのJavaScriptのネイティブ配列を作りました。次に`Float32Array`型の[TypedArrays](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray)に変換します。`BufferAttribute`はネイティブ配列ではなくTypedArrayである必要があります。さらにそれぞれの`BufferAttribute`に対して「1つのvertexに対していくつの要素が必要か」を指定する必要があります。例えばpositionやnormalsは3次元なので1つのvertexつき3つの要素を必要とします。UVはテクスチャ上の2次元の点なので2つの要素を必要とします。
  94. {{{example url="../threejs-custom-buffergeometry-cube.html"}}}
  95. かなり大量のデータです。この配列からvertexを選ぶときにはインデックスを使います。1つの三角形は3つのvertexで構成されていて2つの三角形が1つのfaceを作っています。これが6枚で1つの立方体を構成しています。1つのfaceを構成する2つの三角形を作っているvertexは2つが同じデータを持っています。position, normal, UVすべて同じです。そこで重複しているデータを1つ消して1つにして、そのデータを別のインデックスで指定します。
  96. ではまず重複したデータを1つにします。
  97. ```js
  98. const vertices = [
  99. // front
  100. { pos: [-1, -1, 1], norm: [ 0, 0, 1], uv: [0, 0], }, // 0
  101. { pos: [ 1, -1, 1], norm: [ 0, 0, 1], uv: [1, 0], }, // 1
  102. { pos: [-1, 1, 1], norm: [ 0, 0, 1], uv: [0, 1], }, // 2
  103. -
  104. - { pos: [-1, 1, 1], norm: [ 0, 0, 1], uv: [0, 1], },
  105. - { pos: [ 1, -1, 1], norm: [ 0, 0, 1], uv: [1, 0], },
  106. { pos: [ 1, 1, 1], norm: [ 0, 0, 1], uv: [1, 1], }, // 3
  107. // right
  108. { pos: [ 1, -1, 1], norm: [ 1, 0, 0], uv: [0, 0], }, // 4
  109. { pos: [ 1, -1, -1], norm: [ 1, 0, 0], uv: [1, 0], }, // 5
  110. -
  111. - { pos: [ 1, 1, 1], norm: [ 1, 0, 0], uv: [0, 1], },
  112. - { pos: [ 1, -1, -1], norm: [ 1, 0, 0], uv: [1, 0], },
  113. { pos: [ 1, 1, 1], norm: [ 1, 0, 0], uv: [0, 1], }, // 6
  114. { pos: [ 1, 1, -1], norm: [ 1, 0, 0], uv: [1, 1], }, // 7
  115. // back
  116. { pos: [ 1, -1, -1], norm: [ 0, 0, -1], uv: [0, 0], }, // 8
  117. { pos: [-1, -1, -1], norm: [ 0, 0, -1], uv: [1, 0], }, // 9
  118. -
  119. - { pos: [ 1, 1, -1], norm: [ 0, 0, -1], uv: [0, 1], },
  120. - { pos: [-1, -1, -1], norm: [ 0, 0, -1], uv: [1, 0], },
  121. { pos: [ 1, 1, -1], norm: [ 0, 0, -1], uv: [0, 1], }, // 10
  122. { pos: [-1, 1, -1], norm: [ 0, 0, -1], uv: [1, 1], }, // 11
  123. // left
  124. { pos: [-1, -1, -1], norm: [-1, 0, 0], uv: [0, 0], }, // 12
  125. { pos: [-1, -1, 1], norm: [-1, 0, 0], uv: [1, 0], }, // 13
  126. -
  127. - { pos: [-1, 1, -1], norm: [-1, 0, 0], uv: [0, 1], },
  128. - { pos: [-1, -1, 1], norm: [-1, 0, 0], uv: [1, 0], },
  129. { pos: [-1, 1, -1], norm: [-1, 0, 0], uv: [0, 1], }, // 14
  130. { pos: [-1, 1, 1], norm: [-1, 0, 0], uv: [1, 1], }, // 15
  131. // top
  132. { pos: [ 1, 1, -1], norm: [ 0, 1, 0], uv: [0, 0], }, // 16
  133. { pos: [-1, 1, -1], norm: [ 0, 1, 0], uv: [1, 0], }, // 17
  134. -
  135. - { pos: [ 1, 1, 1], norm: [ 0, 1, 0], uv: [0, 1], },
  136. - { pos: [-1, 1, -1], norm: [ 0, 1, 0], uv: [1, 0], },
  137. { pos: [ 1, 1, 1], norm: [ 0, 1, 0], uv: [0, 1], }, // 18
  138. { pos: [-1, 1, 1], norm: [ 0, 1, 0], uv: [1, 1], }, // 19
  139. // bottom
  140. { pos: [ 1, -1, 1], norm: [ 0, -1, 0], uv: [0, 0], }, // 20
  141. { pos: [-1, -1, 1], norm: [ 0, -1, 0], uv: [1, 0], }, // 21
  142. -
  143. - { pos: [ 1, -1, -1], norm: [ 0, -1, 0], uv: [0, 1], },
  144. - { pos: [-1, -1, 1], norm: [ 0, -1, 0], uv: [1, 0], },
  145. { pos: [ 1, -1, -1], norm: [ 0, -1, 0], uv: [0, 1], }, // 22
  146. { pos: [-1, -1, -1], norm: [ 0, -1, 0], uv: [1, 1], }, // 23
  147. ];
  148. ```
  149. はい、24個になりました。これに対して36個のインデックスを指定して36個のvertexを作ります。`BufferGeometry.setIndex`により36個のインデックスを使って12個の三角形を作ります。
  150. ```js
  151. geometry.setAttribute(
  152. 'position',
  153. new THREE.BufferAttribute(positions, positionNumComponents));
  154. geometry.setAttribute(
  155. 'normal',
  156. new THREE.BufferAttribute(normals, normalNumComponents));
  157. geometry.setAttribute(
  158. 'uv',
  159. new THREE.BufferAttribute(uvs, uvNumComponents));
  160. +geometry.setIndex([
  161. + 0, 1, 2, 2, 1, 3, // front
  162. + 4, 5, 6, 6, 5, 7, // right
  163. + 8, 9, 10, 10, 9, 11, // back
  164. + 12, 13, 14, 14, 13, 15, // left
  165. + 16, 17, 18, 18, 17, 19, // top
  166. + 20, 21, 22, 22, 21, 23, // bottom
  167. +]);
  168. ```
  169. {{{example url="../threejs-custom-buffergeometry-cube-indexed.html"}}}
  170. `Geometry`と同じように`BufferGeometry`も[`computeVertexNormals`](BufferGeometry.computeVertexNormals)メソッドを持っています。これは特に指定がない場合に自動的にnormalを計算するメソッドです。ただし`Geometry`の場合と違いvertexがfaceによって共有されていないために`computeVertexNormals`の結果も少し違います。
  171. <div class="spread">
  172. <div>
  173. <div data-diagram="bufferGeometryCylinder"></div>
  174. </div>
  175. </div>
  176. シリンダーで`computeVertexNormals`の違いを比較してみましょう。よく見ると左のシリンダーには縫い目が見えると思います。これはvertexを共有することができないためにUVも異なるためです。ちょっとしたことですが、気になるときは自分でnormalを指定すれば良いだけです。
  177. ネイティブの配列を使う代わりに[TypedArrays](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray)を使うこともできます。TypedArrayは最初に配列の大きさを指定する必要があるため少し面倒です。ネイティブの配列は`push`で追加して`length`で配列の長さを確認することができます。TypedArrayには`push`メソッドがないのであらかじめ用意した配列に注意しながら要素を入れていく必要があります。
  178. この例では最初に大きなデータを使っているので配列の長さを意識することはそれほど大変ではありません。
  179. ```js
  180. -const positions = [];
  181. -const normals = [];
  182. -const uvs = [];
  183. +const numVertices = vertices.length;
  184. +const positionNumComponents = 3;
  185. +const normalNumComponents = 3;
  186. +const uvNumComponents = 2;
  187. +const positions = new Float32Array(numVertices * positionNumComponents);
  188. +const normals = new Float32Array(numVertices * normalNumComponents);
  189. +const uvs = new Float32Array(numVertices * uvNumComponents);
  190. +let posNdx = 0;
  191. +let nrmNdx = 0;
  192. +let uvNdx = 0;
  193. for (const vertex of vertices) {
  194. - positions.push(...vertex.pos);
  195. - normals.push(...vertex.norm);
  196. - uvs.push(...vertex.uv);
  197. + positions.set(vertex.pos, posNdx);
  198. + normals.set(vertex.norm, nrmNdx);
  199. + uvs.set(vertex.uv, uvNdx);
  200. + posNdx += positionNumComponents;
  201. + nrmNdx += normalNumComponents;
  202. + uvNdx += uvNumComponents;
  203. }
  204. geometry.setAttribute(
  205. 'position',
  206. - new THREE.BufferAttribute(new Float32Array(positions), positionNumComponents));
  207. + new THREE.BufferAttribute(positions, positionNumComponents));
  208. geometry.setAttribute(
  209. 'normal',
  210. - new THREE.BufferAttribute(new Float32Array(normals), normalNumComponents));
  211. + new THREE.BufferAttribute(normals, normalNumComponents));
  212. geometry.setAttribute(
  213. 'uv',
  214. - new THREE.BufferAttribute(new Float32Array(uvs), uvNumComponents));
  215. + new THREE.BufferAttribute(uvs, uvNumComponents));
  216. geometry.setIndex([
  217. 0, 1, 2, 2, 1, 3, // front
  218. 4, 5, 6, 6, 5, 7, // right
  219. 8, 9, 10, 10, 9, 11, // back
  220. 12, 13, 14, 14, 13, 15, // left
  221. 16, 17, 18, 18, 17, 19, // top
  222. 20, 21, 22, 22, 21, 23, // bottom
  223. ]);
  224. ```
  225. {{{example url="../threejs-custom-buffergeometry-cube-typedarrays.html"}}}
  226. TypedArrayはプログラムが走っている状態でvertexの編集をしたいときに便利です。
  227. 良い例が思いつかないのでとりあえずメッシュの四角形が出たり入ったりする球体を作ってみます。
  228. 球体の位置とindexを生成するコードです。四角形の中でvertexを共有していますが四角形と四角形でvertexを共有することはありません。共有してしまうと1つの四角形が出たり入ったりするたびに隣の四角形が移動してしまいます。今回は別々に移動させたいのでそうしています。
  229. 面倒なので3つの`Object3D`階層を用意して球体のvertexを計算します。くわしくは[たくさんのオブジェクトを最適化するこの記事](threejs-optimize-lots-of-objects.html)をご覧ください。
  230. ```js
  231. function makeSpherePositions(segmentsAround, segmentsDown) {
  232. const numVertices = segmentsAround * segmentsDown * 6;
  233. const numComponents = 3;
  234. const positions = new Float32Array(numVertices * numComponents);
  235. const indices = [];
  236. const longHelper = new THREE.Object3D();
  237. const latHelper = new THREE.Object3D();
  238. const pointHelper = new THREE.Object3D();
  239. longHelper.add(latHelper);
  240. latHelper.add(pointHelper);
  241. pointHelper.position.z = 1;
  242. const temp = new THREE.Vector3();
  243. function getPoint(lat, long) {
  244. latHelper.rotation.x = lat;
  245. longHelper.rotation.y = long;
  246. longHelper.updateMatrixWorld(true);
  247. return pointHelper.getWorldPosition(temp).toArray();
  248. }
  249. let posNdx = 0;
  250. let ndx = 0;
  251. for (let down = 0; down < segmentsDown; ++down) {
  252. const v0 = down / segmentsDown;
  253. const v1 = (down + 1) / segmentsDown;
  254. const lat0 = (v0 - 0.5) * Math.PI;
  255. const lat1 = (v1 - 0.5) * Math.PI;
  256. for (let across = 0; across < segmentsAround; ++across) {
  257. const u0 = across / segmentsAround;
  258. const u1 = (across + 1) / segmentsAround;
  259. const long0 = u0 * Math.PI * 2;
  260. const long1 = u1 * Math.PI * 2;
  261. positions.set(getPoint(lat0, long0), posNdx); posNdx += numComponents;
  262. positions.set(getPoint(lat1, long0), posNdx); posNdx += numComponents;
  263. positions.set(getPoint(lat0, long1), posNdx); posNdx += numComponents;
  264. positions.set(getPoint(lat1, long1), posNdx); posNdx += numComponents;
  265. indices.push(
  266. ndx, ndx + 1, ndx + 2,
  267. ndx + 2, ndx + 1, ndx + 3,
  268. );
  269. ndx += 4;
  270. }
  271. }
  272. return {positions, indices};
  273. }
  274. ```
  275. こんな感じです。
  276. ```js
  277. const segmentsAround = 24;
  278. const segmentsDown = 16;
  279. const {positions, indices} = makeSpherePositions(segmentsAround, segmentsDown);
  280. ```
  281. returnされているpositionは単位球(半径が1の球体)なのでそのままこのデータをnormalに使えます。
  282. ```js
  283. const normals = positions.slice();
  284. ```
  285. attributeも設定しましょう。
  286. ```js
  287. const geometry = new THREE.BufferGeometry();
  288. const positionNumComponents = 3;
  289. const normalNumComponents = 3;
  290. +const positionAttribute = new THREE.BufferAttribute(positions, positionNumComponents);
  291. +positionAttribute.setUsage(THREE.DynamicDrawUsage);
  292. geometry.setAttribute(
  293. 'position',
  294. + positionAttribute);
  295. geometry.setAttribute(
  296. 'normal',
  297. new THREE.BufferAttribute(normals, normalNumComponents));
  298. geometry.setIndex(indices);
  299. ```
  300. position attributeに対する参照を保存しています。dynamicに指定しているところも注意が必要です。これはTHREE.jsに「これからこのattributeは変更が加えられる」ことを教えます。renderループではpositionを毎度アップデートします。
  301. ```js
  302. const temp = new THREE.Vector3();
  303. ...
  304. for (let i = 0; i < positions.length; i += 3) {
  305. const quad = (i / 12 | 0);
  306. const ringId = quad / segmentsAround | 0;
  307. const ringQuadId = quad % segmentsAround;
  308. const ringU = ringQuadId / segmentsAround;
  309. const angle = ringU * Math.PI * 2;
  310. temp.fromArray(normals, i);
  311. temp.multiplyScalar(THREE.MathUtils.lerp(1, 1.4, Math.sin(time + ringId + angle) * .5 + .5));
  312. temp.toArray(positions, i);
  313. }
  314. positionAttribute.needsUpdate = true;
  315. ```
  316. 最後に`positionAttribute.needsUpdate`を設定してTHREE.jsに変更が必要であることを伝えます。
  317. {{{example url="../threejs-custom-buffergeometry-dynamic.html"}}}
  318. `BufferGeometry`を作って`BufferAttribute`をアップデートする方法を紹介しました。
  319. <canvas id="c"></canvas>
  320. <script type="module" src="resources/threejs-custom-buffergeometry.js"></script>