voxel-geometry.html 43 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133
  1. <!DOCTYPE html><html lang="en"><head>
  2. <meta charset="utf-8">
  3. <title>Voxel(Minecraft Like) Geometry</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 – Voxel(Minecraft Like) Geometry">
  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>Voxel(Minecraft Like) Geometry</h1>
  25. </div>
  26. <div class="lesson">
  27. <div class="lesson-main">
  28. <p>I've seen this topic come up more than once in various places.
  29. That is basically, "How do I make a voxel display like Minecraft".</p>
  30. <p>Most people first attempt this by making a cube geometry and then
  31. making a mesh at each voxel position. Just for fun I tried
  32. this. I made a 16777216 element <code class="notranslate" translate="no">Uint8Array</code> to represent
  33. a 256x256x256 cube of voxels.</p>
  34. <pre class="prettyprint showlinemods notranslate lang-js" translate="no">const cellSize = 256;
  35. const cell = new Uint8Array(cellSize * cellSize * cellSize);
  36. </pre>
  37. <p>I then made a single layer with a kind of hills of
  38. sine waves like this</p>
  39. <pre class="prettyprint showlinemods notranslate lang-js" translate="no">for (let y = 0; y &lt; cellSize; ++y) {
  40. for (let z = 0; z &lt; cellSize; ++z) {
  41. for (let x = 0; x &lt; cellSize; ++x) {
  42. const height = (Math.sin(x / cellSize * Math.PI * 4) + Math.sin(z / cellSize * Math.PI * 6)) * 20 + cellSize / 2;
  43. if (height &gt; y &amp;&amp; height &lt; y + 1) {
  44. const offset = y * cellSize * cellSize +
  45. z * cellSize +
  46. x;
  47. cell[offset] = 1;
  48. }
  49. }
  50. }
  51. }
  52. </pre>
  53. <p>I then walked through all the cells and if they were not
  54. 0 I created a mesh with a cube.</p>
  55. <pre class="prettyprint showlinemods notranslate lang-js" translate="no">const geometry = new THREE.BoxGeometry(1, 1, 1);
  56. const material = new THREE.MeshPhongMaterial({color: 'green'});
  57. for (let y = 0; y &lt; cellSize; ++y) {
  58. for (let z = 0; z &lt; cellSize; ++z) {
  59. for (let x = 0; x &lt; cellSize; ++x) {
  60. const offset = y * cellSize * cellSize +
  61. z * cellSize +
  62. x;
  63. const block = cell[offset];
  64. const mesh = new THREE.Mesh(geometry, material);
  65. mesh.position.set(x, y, z);
  66. scene.add(mesh);
  67. }
  68. }
  69. }
  70. </pre>
  71. <p>The rest of the code is based on the example from
  72. <a href="rendering-on-demand.html">the article on rendering on demand</a>.</p>
  73. <p></p><div translate="no" class="threejs_example_container notranslate">
  74. <div><iframe class="threejs_example notranslate" translate="no" style=" " src="/manual/examples/resources/editor.html?url=/manual/examples/voxel-geometry-separate-cubes.html"></iframe></div>
  75. <a class="threejs_center" href="/manual/examples/voxel-geometry-separate-cubes.html" target="_blank">click here to open in a separate window</a>
  76. </div>
  77. <p></p>
  78. <p>It takes a while to start and if you try to move the camera
  79. it's likely too slow. Like <a href="optimize-lots-of-objects.html">the article on how to optimize lots of objects</a>
  80. the problem is there are just way too many objects. 256x256
  81. is 65536 boxes!</p>
  82. <p>Using <a href="rendering-on-demand.html">the technique of merging the geometry</a>
  83. will fix the issue for this example but what if instead of just making
  84. a single layer we filled in everything below the ground with voxel.
  85. In other words change the loop filling in the voxels to this</p>
  86. <pre class="prettyprint showlinemods notranslate lang-js" translate="no">for (let y = 0; y &lt; cellSize; ++y) {
  87. for (let z = 0; z &lt; cellSize; ++z) {
  88. for (let x = 0; x &lt; cellSize; ++x) {
  89. const height = (Math.sin(x / cellSize * Math.PI * 4) + Math.sin(z / cellSize * Math.PI * 6)) * 20 + cellSize / 2;
  90. - if (height &gt; y &amp;&amp; height &lt; y + 1) {
  91. + if (height &lt; y + 1) {
  92. const offset = y * cellSize * cellSize +
  93. z * cellSize +
  94. x;
  95. cell[offset] = 1;
  96. }
  97. }
  98. }
  99. }
  100. </pre>
  101. <p>I tried it once just to see the results. It churned for
  102. about a minute and then crashed with <em>out of memory</em> 😅</p>
  103. <p>There are several issues but the biggest issue is
  104. we're making all these faces inside the cubes that
  105. we can actually never see.</p>
  106. <p>In other words lets say we have a box of voxels
  107. 3x2x2. By merging cubes we're getting this</p>
  108. <div class="spread">
  109. <div data-diagram="mergedCubes" style="height: 300px;"></div>
  110. </div>
  111. <p>but we really want this</p>
  112. <div class="spread">
  113. <div data-diagram="culledCubes" style="height: 300px;"></div>
  114. </div>
  115. <p>In the top box there are faces between the voxels. Faces
  116. that are a waste since they can't be seen. It's not just
  117. one face between each voxel, there are 2 faces, one for
  118. each voxel facing its neighbor that are a waste. All these extra faces,
  119. especially for a large volume of voxels will kill performance.</p>
  120. <p>It should be clear that we can't just merge geometry.
  121. We need to build it ourselves, taking into account that
  122. if a voxel has an adjacent neighbor it doesn't need the
  123. face facing that neighbor.</p>
  124. <p>The next issue is that 256x256x256 is just too big. 16meg is a lot of memory and
  125. if nothing else in much of the space nothing is there so that's a lot of wasted
  126. memory. It's also a huge number of voxels, 16 million! That's too much to
  127. consider at once.</p>
  128. <p>A solution is to divide the area into smaller areas.
  129. Any area that has nothing in it needs no storage. Let's use
  130. 32x32x32 areas (that's 32k) and only create an area if something is in it.
  131. We'll call one of these larger 32x32x32 areas a "cell".</p>
  132. <p>Let's break this into pieces. First let's make a class to manage the voxel data.</p>
  133. <pre class="prettyprint showlinemods notranslate lang-js" translate="no">class VoxelWorld {
  134. constructor(cellSize) {
  135. this.cellSize = cellSize;
  136. }
  137. }
  138. </pre>
  139. <p>Let's make the function that makes geometry for a cell.
  140. Let's assume you pass in a cell position.
  141. In other words if you want the geometry for the cell that covers voxels (0-31x, 0-31y, 0-31z)
  142. then you'd pass in 0,0,0. For the cell that covers voxels (32-63x, 0-31y, 0-31z) you'd
  143. pass in 1,0,0.</p>
  144. <p>We need to be able to check the neighboring voxels so let's assume our class
  145. has a function <code class="notranslate" translate="no">getVoxel</code> that given a voxel position returns the value of
  146. the voxel there. In other words if you pass it 35,0,0 and the cellSize is 32
  147. it's going to look at cell 1,0,0 and in that cell it will look at voxel 3,0,0.
  148. Using this function we can look at a voxel's neighboring voxels even if they
  149. happen to be in neighboring cells.</p>
  150. <pre class="prettyprint showlinemods notranslate lang-js" translate="no">class VoxelWorld {
  151. constructor(cellSize) {
  152. this.cellSize = cellSize;
  153. }
  154. + generateGeometryDataForCell(cellX, cellY, cellZ) {
  155. + const {cellSize} = this;
  156. + const startX = cellX * cellSize;
  157. + const startY = cellY * cellSize;
  158. + const startZ = cellZ * cellSize;
  159. +
  160. + for (let y = 0; y &lt; cellSize; ++y) {
  161. + const voxelY = startY + y;
  162. + for (let z = 0; z &lt; cellSize; ++z) {
  163. + const voxelZ = startZ + z;
  164. + for (let x = 0; x &lt; cellSize; ++x) {
  165. + const voxelX = startX + x;
  166. + const voxel = this.getVoxel(voxelX, voxelY, voxelZ);
  167. + if (voxel) {
  168. + for (const {dir} of VoxelWorld.faces) {
  169. + const neighbor = this.getVoxel(
  170. + voxelX + dir[0],
  171. + voxelY + dir[1],
  172. + voxelZ + dir[2]);
  173. + if (!neighbor) {
  174. + // this voxel has no neighbor in this direction so we need a face
  175. + // here.
  176. + }
  177. + }
  178. + }
  179. + }
  180. + }
  181. + }
  182. + }
  183. }
  184. +VoxelWorld.faces = [
  185. + { // left
  186. + dir: [ -1, 0, 0, ],
  187. + },
  188. + { // right
  189. + dir: [ 1, 0, 0, ],
  190. + },
  191. + { // bottom
  192. + dir: [ 0, -1, 0, ],
  193. + },
  194. + { // top
  195. + dir: [ 0, 1, 0, ],
  196. + },
  197. + { // back
  198. + dir: [ 0, 0, -1, ],
  199. + },
  200. + { // front
  201. + dir: [ 0, 0, 1, ],
  202. + },
  203. +];
  204. </pre>
  205. <p>So using the code above we know when we need a face. Let's generate the faces.</p>
  206. <pre class="prettyprint showlinemods notranslate lang-js" translate="no">class VoxelWorld {
  207. constructor(cellSize) {
  208. this.cellSize = cellSize;
  209. }
  210. generateGeometryDataForCell(cellX, cellY, cellZ) {
  211. const {cellSize} = this;
  212. + const positions = [];
  213. + const normals = [];
  214. + const indices = [];
  215. const startX = cellX * cellSize;
  216. const startY = cellY * cellSize;
  217. const startZ = cellZ * cellSize;
  218. for (let y = 0; y &lt; cellSize; ++y) {
  219. const voxelY = startY + y;
  220. for (let z = 0; z &lt; cellSize; ++z) {
  221. const voxelZ = startZ + z;
  222. for (let x = 0; x &lt; cellSize; ++x) {
  223. const voxelX = startX + x;
  224. const voxel = this.getVoxel(voxelX, voxelY, voxelZ);
  225. if (voxel) {
  226. - for (const {dir} of VoxelWorld.faces) {
  227. + for (const {dir, corners} of VoxelWorld.faces) {
  228. const neighbor = this.getVoxel(
  229. voxelX + dir[0],
  230. voxelY + dir[1],
  231. voxelZ + dir[2]);
  232. if (!neighbor) {
  233. // this voxel has no neighbor in this direction so we need a face.
  234. + const ndx = positions.length / 3;
  235. + for (const pos of corners) {
  236. + positions.push(pos[0] + x, pos[1] + y, pos[2] + z);
  237. + normals.push(...dir);
  238. + }
  239. + indices.push(
  240. + ndx, ndx + 1, ndx + 2,
  241. + ndx + 2, ndx + 1, ndx + 3,
  242. + );
  243. }
  244. }
  245. }
  246. }
  247. }
  248. }
  249. + return {
  250. + positions,
  251. + normals,
  252. + indices,
  253. };
  254. }
  255. }
  256. VoxelWorld.faces = [
  257. { // left
  258. dir: [ -1, 0, 0, ],
  259. + corners: [
  260. + [ 0, 1, 0 ],
  261. + [ 0, 0, 0 ],
  262. + [ 0, 1, 1 ],
  263. + [ 0, 0, 1 ],
  264. + ],
  265. },
  266. { // right
  267. dir: [ 1, 0, 0, ],
  268. + corners: [
  269. + [ 1, 1, 1 ],
  270. + [ 1, 0, 1 ],
  271. + [ 1, 1, 0 ],
  272. + [ 1, 0, 0 ],
  273. + ],
  274. },
  275. { // bottom
  276. dir: [ 0, -1, 0, ],
  277. + corners: [
  278. + [ 1, 0, 1 ],
  279. + [ 0, 0, 1 ],
  280. + [ 1, 0, 0 ],
  281. + [ 0, 0, 0 ],
  282. + ],
  283. },
  284. { // top
  285. dir: [ 0, 1, 0, ],
  286. + corners: [
  287. + [ 0, 1, 1 ],
  288. + [ 1, 1, 1 ],
  289. + [ 0, 1, 0 ],
  290. + [ 1, 1, 0 ],
  291. + ],
  292. },
  293. { // back
  294. dir: [ 0, 0, -1, ],
  295. + corners: [
  296. + [ 1, 0, 0 ],
  297. + [ 0, 0, 0 ],
  298. + [ 1, 1, 0 ],
  299. + [ 0, 1, 0 ],
  300. + ],
  301. },
  302. { // front
  303. dir: [ 0, 0, 1, ],
  304. + corners: [
  305. + [ 0, 0, 1 ],
  306. + [ 1, 0, 1 ],
  307. + [ 0, 1, 1 ],
  308. + [ 1, 1, 1 ],
  309. + ],
  310. },
  311. ];
  312. </pre>
  313. <p>The code above would make basic geometry data for us. We just need to supply
  314. the <code class="notranslate" translate="no">getVoxel</code> function. Let's start with just one hard coded cell.</p>
  315. <pre class="prettyprint showlinemods notranslate lang-js" translate="no">class VoxelWorld {
  316. constructor(cellSize) {
  317. this.cellSize = cellSize;
  318. + this.cell = new Uint8Array(cellSize * cellSize * cellSize);
  319. }
  320. + getCellForVoxel(x, y, z) {
  321. + const {cellSize} = this;
  322. + const cellX = Math.floor(x / cellSize);
  323. + const cellY = Math.floor(y / cellSize);
  324. + const cellZ = Math.floor(z / cellSize);
  325. + if (cellX !== 0 || cellY !== 0 || cellZ !== 0) {
  326. + return null
  327. + }
  328. + return this.cell;
  329. + }
  330. + getVoxel(x, y, z) {
  331. + const cell = this.getCellForVoxel(x, y, z);
  332. + if (!cell) {
  333. + return 0;
  334. + }
  335. + const {cellSize} = this;
  336. + const voxelX = THREE.MathUtils.euclideanModulo(x, cellSize) | 0;
  337. + const voxelY = THREE.MathUtils.euclideanModulo(y, cellSize) | 0;
  338. + const voxelZ = THREE.MathUtils.euclideanModulo(z, cellSize) | 0;
  339. + const voxelOffset = voxelY * cellSize * cellSize +
  340. + voxelZ * cellSize +
  341. + voxelX;
  342. + return cell[voxelOffset];
  343. + }
  344. generateGeometryDataForCell(cellX, cellY, cellZ) {
  345. ...
  346. }
  347. </pre>
  348. <p>This seems like it would work. Let's make a <code class="notranslate" translate="no">setVoxel</code> function
  349. so we can set some data.</p>
  350. <pre class="prettyprint showlinemods notranslate lang-js" translate="no">class VoxelWorld {
  351. constructor(cellSize) {
  352. this.cellSize = cellSize;
  353. this.cell = new Uint8Array(cellSize * cellSize * cellSize);
  354. }
  355. getCellForVoxel(x, y, z) {
  356. const {cellSize} = this;
  357. const cellX = Math.floor(x / cellSize);
  358. const cellY = Math.floor(y / cellSize);
  359. const cellZ = Math.floor(z / cellSize);
  360. if (cellX !== 0 || cellY !== 0 || cellZ !== 0) {
  361. return null
  362. }
  363. return this.cell;
  364. }
  365. + setVoxel(x, y, z, v) {
  366. + let cell = this.getCellForVoxel(x, y, z);
  367. + if (!cell) {
  368. + return; // TODO: add a new cell?
  369. + }
  370. + const {cellSize} = this;
  371. + const voxelX = THREE.MathUtils.euclideanModulo(x, cellSize) | 0;
  372. + const voxelY = THREE.MathUtils.euclideanModulo(y, cellSize) | 0;
  373. + const voxelZ = THREE.MathUtils.euclideanModulo(z, cellSize) | 0;
  374. + const voxelOffset = voxelY * cellSize * cellSize +
  375. + voxelZ * cellSize +
  376. + voxelX;
  377. + cell[voxelOffset] = v;
  378. + }
  379. getVoxel(x, y, z) {
  380. const cell = this.getCellForVoxel(x, y, z);
  381. if (!cell) {
  382. return 0;
  383. }
  384. const {cellSize} = this;
  385. const voxelX = THREE.MathUtils.euclideanModulo(x, cellSize) | 0;
  386. const voxelY = THREE.MathUtils.euclideanModulo(y, cellSize) | 0;
  387. const voxelZ = THREE.MathUtils.euclideanModulo(z, cellSize) | 0;
  388. const voxelOffset = voxelY * cellSize * cellSize +
  389. voxelZ * cellSize +
  390. voxelX;
  391. return cell[voxelOffset];
  392. }
  393. generateGeometryDataForCell(cellX, cellY, cellZ) {
  394. ...
  395. }
  396. </pre>
  397. <p>Hmmm, I see a lot of repeated code. Let's fix that up</p>
  398. <pre class="prettyprint showlinemods notranslate lang-js" translate="no">class VoxelWorld {
  399. constructor(cellSize) {
  400. this.cellSize = cellSize;
  401. + this.cellSliceSize = cellSize * cellSize;
  402. this.cell = new Uint8Array(cellSize * cellSize * cellSize);
  403. }
  404. getCellForVoxel(x, y, z) {
  405. const {cellSize} = this;
  406. const cellX = Math.floor(x / cellSize);
  407. const cellY = Math.floor(y / cellSize);
  408. const cellZ = Math.floor(z / cellSize);
  409. if (cellX !== 0 || cellY !== 0 || cellZ !== 0) {
  410. return null;
  411. }
  412. return this.cell;
  413. }
  414. + computeVoxelOffset(x, y, z) {
  415. + const {cellSize, cellSliceSize} = this;
  416. + const voxelX = THREE.MathUtils.euclideanModulo(x, cellSize) | 0;
  417. + const voxelY = THREE.MathUtils.euclideanModulo(y, cellSize) | 0;
  418. + const voxelZ = THREE.MathUtils.euclideanModulo(z, cellSize) | 0;
  419. + return voxelY * cellSliceSize +
  420. + voxelZ * cellSize +
  421. + voxelX;
  422. + }
  423. setVoxel(x, y, z, v) {
  424. const cell = this.getCellForVoxel(x, y, z);
  425. if (!cell) {
  426. return; // TODO: add a new cell?
  427. }
  428. - const {cellSize} = this;
  429. - const voxelX = THREE.MathUtils.euclideanModulo(x, cellSize) | 0;
  430. - const voxelY = THREE.MathUtils.euclideanModulo(y, cellSize) | 0;
  431. - const voxelZ = THREE.MathUtils.euclideanModulo(z, cellSize) | 0;
  432. - const voxelOffset = voxelY * cellSize * cellSize +
  433. - voxelZ * cellSize +
  434. - voxelX;
  435. + const voxelOffset = this.computeVoxelOffset(x, y, z);
  436. cell[voxelOffset] = v;
  437. }
  438. getVoxel(x, y, z) {
  439. const cell = this.getCellForVoxel(x, y, z);
  440. if (!cell) {
  441. return 0;
  442. }
  443. - const {cellSize} = this;
  444. - const voxelX = THREE.MathUtils.euclideanModulo(x, cellSize) | 0;
  445. - const voxelY = THREE.MathUtils.euclideanModulo(y, cellSize) | 0;
  446. - const voxelZ = THREE.MathUtils.euclideanModulo(z, cellSize) | 0;
  447. - const voxelOffset = voxelY * cellSize * cellSize +
  448. - voxelZ * cellSize +
  449. - voxelX;
  450. + const voxelOffset = this.computeVoxelOffset(x, y, z);
  451. return cell[voxelOffset];
  452. }
  453. generateGeometryDataForCell(cellX, cellY, cellZ) {
  454. ...
  455. }
  456. </pre>
  457. <p>Now let's make some code to fill out the first cell with voxels.</p>
  458. <pre class="prettyprint showlinemods notranslate lang-js" translate="no">const cellSize = 32;
  459. const world = new VoxelWorld(cellSize);
  460. for (let y = 0; y &lt; cellSize; ++y) {
  461. for (let z = 0; z &lt; cellSize; ++z) {
  462. for (let x = 0; x &lt; cellSize; ++x) {
  463. const height = (Math.sin(x / cellSize * Math.PI * 2) + Math.sin(z / cellSize * Math.PI * 3)) * (cellSize / 6) + (cellSize / 2);
  464. if (y &lt; height) {
  465. world.setVoxel(x, y, z, 1);
  466. }
  467. }
  468. }
  469. }
  470. </pre>
  471. <p>and some code to actually generate geometry like we covered in
  472. <a href="custom-buffergeometry.html">the article on custom BufferGeometry</a>.</p>
  473. <pre class="prettyprint showlinemods notranslate lang-js" translate="no">const {positions, normals, indices} = world.generateGeometryDataForCell(0, 0, 0);
  474. const geometry = new THREE.BufferGeometry();
  475. const material = new THREE.MeshLambertMaterial({color: 'green'});
  476. const positionNumComponents = 3;
  477. const normalNumComponents = 3;
  478. geometry.setAttribute(
  479. 'position',
  480. new THREE.BufferAttribute(new Float32Array(positions), positionNumComponents));
  481. geometry.setAttribute(
  482. 'normal',
  483. new THREE.BufferAttribute(new Float32Array(normals), normalNumComponents));
  484. geometry.setIndex(indices);
  485. const mesh = new THREE.Mesh(geometry, material);
  486. scene.add(mesh);
  487. </pre>
  488. <p>let's try it</p>
  489. <p></p><div translate="no" class="threejs_example_container notranslate">
  490. <div><iframe class="threejs_example notranslate" translate="no" style=" " src="/manual/examples/resources/editor.html?url=/manual/examples/voxel-geometry-culled-faces.html"></iframe></div>
  491. <a class="threejs_center" href="/manual/examples/voxel-geometry-culled-faces.html" target="_blank">click here to open in a separate window</a>
  492. </div>
  493. <p></p>
  494. <p>That seems to be working! Okay, let's add in textures.</p>
  495. <p>Searching on the net I found <a href="https://www.minecraftforum.net/forums/mapping-and-modding-java-edition/resource-packs/1245961-16x-1-7-4-wip-flourish">this set</a>
  496. of <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/">CC-BY-NC-SA</a> licensed minecraft textures
  497. by <a href="https://www.minecraftforum.net/members/Joshtimus">Joshtimus</a>.
  498. I picked a few at random and built this <a href="https://www.google.com/search?q=texture+atlas">texture atlas</a>.</p>
  499. <div class="threejs_center"><img class="checkerboard" src="../examples/resources/images/minecraft/flourish-cc-by-nc-sa.png" style="width: 512px; image-rendering: pixelated;"></div>
  500. <p>To make things simple they are arranged a voxel type per column
  501. where the top row is the side of a voxel. The 2nd row is
  502. the top of voxel, and the 3rd row is the bottom of the voxel.</p>
  503. <p>Knowing that we can add info to our <code class="notranslate" translate="no">VoxelWorld.faces</code> data
  504. to specify for each face which row to use and the UVs to use
  505. for that face.</p>
  506. <pre class="prettyprint showlinemods notranslate lang-js" translate="no">VoxelWorld.faces = [
  507. { // left
  508. + uvRow: 0,
  509. dir: [ -1, 0, 0, ],
  510. corners: [
  511. - [ 0, 1, 0 ],
  512. - [ 0, 0, 0 ],
  513. - [ 0, 1, 1 ],
  514. - [ 0, 0, 1 ],
  515. + { pos: [ 0, 1, 0 ], uv: [ 0, 1 ], },
  516. + { pos: [ 0, 0, 0 ], uv: [ 0, 0 ], },
  517. + { pos: [ 0, 1, 1 ], uv: [ 1, 1 ], },
  518. + { pos: [ 0, 0, 1 ], uv: [ 1, 0 ], },
  519. ],
  520. },
  521. { // right
  522. + uvRow: 0,
  523. dir: [ 1, 0, 0, ],
  524. corners: [
  525. - [ 1, 1, 1 ],
  526. - [ 1, 0, 1 ],
  527. - [ 1, 1, 0 ],
  528. - [ 1, 0, 0 ],
  529. + { pos: [ 1, 1, 1 ], uv: [ 0, 1 ], },
  530. + { pos: [ 1, 0, 1 ], uv: [ 0, 0 ], },
  531. + { pos: [ 1, 1, 0 ], uv: [ 1, 1 ], },
  532. + { pos: [ 1, 0, 0 ], uv: [ 1, 0 ], },
  533. ],
  534. },
  535. { // bottom
  536. + uvRow: 1,
  537. dir: [ 0, -1, 0, ],
  538. corners: [
  539. - [ 1, 0, 1 ],
  540. - [ 0, 0, 1 ],
  541. - [ 1, 0, 0 ],
  542. - [ 0, 0, 0 ],
  543. + { pos: [ 1, 0, 1 ], uv: [ 1, 0 ], },
  544. + { pos: [ 0, 0, 1 ], uv: [ 0, 0 ], },
  545. + { pos: [ 1, 0, 0 ], uv: [ 1, 1 ], },
  546. + { pos: [ 0, 0, 0 ], uv: [ 0, 1 ], },
  547. ],
  548. },
  549. { // top
  550. + uvRow: 2,
  551. dir: [ 0, 1, 0, ],
  552. corners: [
  553. - [ 0, 1, 1 ],
  554. - [ 1, 1, 1 ],
  555. - [ 0, 1, 0 ],
  556. - [ 1, 1, 0 ],
  557. + { pos: [ 0, 1, 1 ], uv: [ 1, 1 ], },
  558. + { pos: [ 1, 1, 1 ], uv: [ 0, 1 ], },
  559. + { pos: [ 0, 1, 0 ], uv: [ 1, 0 ], },
  560. + { pos: [ 1, 1, 0 ], uv: [ 0, 0 ], },
  561. ],
  562. },
  563. { // back
  564. + uvRow: 0,
  565. dir: [ 0, 0, -1, ],
  566. corners: [
  567. - [ 1, 0, 0 ],
  568. - [ 0, 0, 0 ],
  569. - [ 1, 1, 0 ],
  570. - [ 0, 1, 0 ],
  571. + { pos: [ 1, 0, 0 ], uv: [ 0, 0 ], },
  572. + { pos: [ 0, 0, 0 ], uv: [ 1, 0 ], },
  573. + { pos: [ 1, 1, 0 ], uv: [ 0, 1 ], },
  574. + { pos: [ 0, 1, 0 ], uv: [ 1, 1 ], },
  575. ],
  576. },
  577. { // front
  578. + uvRow: 0,
  579. dir: [ 0, 0, 1, ],
  580. corners: [
  581. - [ 0, 0, 1 ],
  582. - [ 1, 0, 1 ],
  583. - [ 0, 1, 1 ],
  584. - [ 1, 1, 1 ],
  585. + { pos: [ 0, 0, 1 ], uv: [ 0, 0 ], },
  586. + { pos: [ 1, 0, 1 ], uv: [ 1, 0 ], },
  587. + { pos: [ 0, 1, 1 ], uv: [ 0, 1 ], },
  588. + { pos: [ 1, 1, 1 ], uv: [ 1, 1 ], },
  589. ],
  590. },
  591. ];
  592. </pre>
  593. <p>And we can update the code to use that data. We need to
  594. know the size of a tile in the texture atlas and the dimensions
  595. of the texture.</p>
  596. <pre class="prettyprint showlinemods notranslate lang-js" translate="no">class VoxelWorld {
  597. - constructor(cellSize) {
  598. - this.cellSize = cellSize;
  599. + constructor(options) {
  600. + this.cellSize = options.cellSize;
  601. + this.tileSize = options.tileSize;
  602. + this.tileTextureWidth = options.tileTextureWidth;
  603. + this.tileTextureHeight = options.tileTextureHeight;
  604. + const {cellSize} = this;
  605. + this.cellSliceSize = cellSize * cellSize;
  606. + this.cell = new Uint8Array(cellSize * cellSize * cellSize);
  607. }
  608. ...
  609. generateGeometryDataForCell(cellX, cellY, cellZ) {
  610. - const {cellSize} = this;
  611. + const {cellSize, tileSize, tileTextureWidth, tileTextureHeight} = this;
  612. const positions = [];
  613. const normals = [];
  614. + const uvs = [];
  615. const indices = [];
  616. const startX = cellX * cellSize;
  617. const startY = cellY * cellSize;
  618. const startZ = cellZ * cellSize;
  619. for (let y = 0; y &lt; cellSize; ++y) {
  620. const voxelY = startY + y;
  621. for (let z = 0; z &lt; cellSize; ++z) {
  622. const voxelZ = startZ + z;
  623. for (let x = 0; x &lt; cellSize; ++x) {
  624. const voxelX = startX + x;
  625. const voxel = this.getVoxel(voxelX, voxelY, voxelZ);
  626. if (voxel) {
  627. const uvVoxel = voxel - 1; // voxel 0 is sky so for UVs we start at 0
  628. // There is a voxel here but do we need faces for it?
  629. - for (const {dir, corners} of VoxelWorld.faces) {
  630. + for (const {dir, corners, uvRow} of VoxelWorld.faces) {
  631. const neighbor = this.getVoxel(
  632. voxelX + dir[0],
  633. voxelY + dir[1],
  634. voxelZ + dir[2]);
  635. if (!neighbor) {
  636. // this voxel has no neighbor in this direction so we need a face.
  637. const ndx = positions.length / 3;
  638. - for (const pos of corners) {
  639. + for (const {pos, uv} of corners) {
  640. positions.push(pos[0] + x, pos[1] + y, pos[2] + z);
  641. normals.push(...dir);
  642. + uvs.push(
  643. + (uvVoxel + uv[0]) * tileSize / tileTextureWidth,
  644. + 1 - (uvRow + 1 - uv[1]) * tileSize / tileTextureHeight);
  645. }
  646. indices.push(
  647. ndx, ndx + 1, ndx + 2,
  648. ndx + 2, ndx + 1, ndx + 3,
  649. );
  650. }
  651. }
  652. }
  653. }
  654. }
  655. }
  656. return {
  657. positions,
  658. normals,
  659. uvs,
  660. indices,
  661. };
  662. }
  663. }
  664. </pre>
  665. <p>We then need to <a href="textures.html">load the texture</a></p>
  666. <pre class="prettyprint showlinemods notranslate lang-js" translate="no">const loader = new THREE.TextureLoader();
  667. const texture = loader.load('resources/images/minecraft/flourish-cc-by-nc-sa.png', render);
  668. texture.magFilter = THREE.NearestFilter;
  669. texture.minFilter = THREE.NearestFilter;
  670. texture.colorSpace = THREE.SRGBColorSpace;
  671. </pre>
  672. <p>and pass the settings to the <code class="notranslate" translate="no">VoxelWorld</code> class</p>
  673. <pre class="prettyprint showlinemods notranslate lang-js" translate="no">+const tileSize = 16;
  674. +const tileTextureWidth = 256;
  675. +const tileTextureHeight = 64;
  676. -const world = new VoxelWorld(cellSize);
  677. +const world = new VoxelWorld({
  678. + cellSize,
  679. + tileSize,
  680. + tileTextureWidth,
  681. + tileTextureHeight,
  682. +});
  683. </pre>
  684. <p>Let's actually use the UVs when we create the geometry
  685. and the texture when we make the material</p>
  686. <pre class="prettyprint showlinemods notranslate lang-js" translate="no">-const {positions, normals, indices} = world.generateGeometryDataForCell(0, 0, 0);
  687. +const {positions, normals, uvs, indices} = world.generateGeometryDataForCell(0, 0, 0);
  688. const geometry = new THREE.BufferGeometry();
  689. -const material = new THREE.MeshLambertMaterial({color: 'green'});
  690. +const material = new THREE.MeshLambertMaterial({
  691. + map: texture,
  692. + side: THREE.DoubleSide,
  693. + alphaTest: 0.1,
  694. + transparent: true,
  695. +});
  696. const positionNumComponents = 3;
  697. const normalNumComponents = 3;
  698. +const uvNumComponents = 2;
  699. geometry.setAttribute(
  700. 'position',
  701. new THREE.BufferAttribute(new Float32Array(positions), positionNumComponents));
  702. geometry.setAttribute(
  703. 'normal',
  704. new THREE.BufferAttribute(new Float32Array(normals), normalNumComponents));
  705. +geometry.setAttribute(
  706. + 'uv',
  707. + new THREE.BufferAttribute(new Float32Array(uvs), uvNumComponents));
  708. geometry.setIndex(indices);
  709. const mesh = new THREE.Mesh(geometry, material);
  710. scene.add(mesh);
  711. </pre>
  712. <p>One last thing, we actually need to set some voxels
  713. to use different textures.</p>
  714. <pre class="prettyprint showlinemods notranslate lang-js" translate="no">for (let y = 0; y &lt; cellSize; ++y) {
  715. for (let z = 0; z &lt; cellSize; ++z) {
  716. for (let x = 0; x &lt; cellSize; ++x) {
  717. const height = (Math.sin(x / cellSize * Math.PI * 2) + Math.sin(z / cellSize * Math.PI * 3)) * (cellSize / 6) + (cellSize / 2);
  718. if (y &lt; height) {
  719. - world.setVoxel(x, y, z, 1);
  720. + world.setVoxel(x, y, z, randInt(1, 17));
  721. }
  722. }
  723. }
  724. }
  725. +function randInt(min, max) {
  726. + return Math.floor(Math.random() * (max - min) + min);
  727. +}
  728. </pre>
  729. <p>and with that we get textures!</p>
  730. <p></p><div translate="no" class="threejs_example_container notranslate">
  731. <div><iframe class="threejs_example notranslate" translate="no" style=" " src="/manual/examples/resources/editor.html?url=/manual/examples/voxel-geometry-culled-faces-with-textures.html"></iframe></div>
  732. <a class="threejs_center" href="/manual/examples/voxel-geometry-culled-faces-with-textures.html" target="_blank">click here to open in a separate window</a>
  733. </div>
  734. <p></p>
  735. <p>Let's make it support more than one cell.</p>
  736. <p>To do this lets store cells in an object using cell ids.
  737. A cell id will just be a cell's coordinates separated by
  738. a comma. In other words if we ask for voxel 35,0,0
  739. that is in cell 1,0,0 so its id is <code class="notranslate" translate="no">"1,0,0"</code>.</p>
  740. <pre class="prettyprint showlinemods notranslate lang-js" translate="no">class VoxelWorld {
  741. constructor(options) {
  742. this.cellSize = options.cellSize;
  743. this.tileSize = options.tileSize;
  744. this.tileTextureWidth = options.tileTextureWidth;
  745. this.tileTextureHeight = options.tileTextureHeight;
  746. const {cellSize} = this;
  747. this.cellSliceSize = cellSize * cellSize;
  748. - this.cell = new Uint8Array(cellSize * cellSize * cellSize);
  749. + this.cells = {};
  750. }
  751. + computeCellId(x, y, z) {
  752. + const {cellSize} = this;
  753. + const cellX = Math.floor(x / cellSize);
  754. + const cellY = Math.floor(y / cellSize);
  755. + const cellZ = Math.floor(z / cellSize);
  756. + return `${cellX},${cellY},${cellZ}`;
  757. + }
  758. + getCellForVoxel(x, y, z) {
  759. - const cellX = Math.floor(x / cellSize);
  760. - const cellY = Math.floor(y / cellSize);
  761. - const cellZ = Math.floor(z / cellSize);
  762. - if (cellX !== 0 || cellY !== 0 || cellZ !== 0) {
  763. - return null;
  764. - }
  765. - return this.cell;
  766. + return this.cells[this.computeCellId(x, y, z)];
  767. }
  768. ...
  769. }
  770. </pre>
  771. <p>and now we can make <code class="notranslate" translate="no">setVoxel</code> add new cells if
  772. we try to set a voxel in a cell that does not yet exist</p>
  773. <pre class="prettyprint showlinemods notranslate lang-js" translate="no"> setVoxel(x, y, z, v) {
  774. - const cell = this.getCellForVoxel(x, y, z);
  775. + let cell = this.getCellForVoxel(x, y, z);
  776. if (!cell) {
  777. - return 0;
  778. + cell = this.addCellForVoxel(x, y, z);
  779. }
  780. const voxelOffset = this.computeVoxelOffset(x, y, z);
  781. cell[voxelOffset] = v;
  782. }
  783. + addCellForVoxel(x, y, z) {
  784. + const cellId = this.computeCellId(x, y, z);
  785. + let cell = this.cells[cellId];
  786. + if (!cell) {
  787. + const {cellSize} = this;
  788. + cell = new Uint8Array(cellSize * cellSize * cellSize);
  789. + this.cells[cellId] = cell;
  790. + }
  791. + return cell;
  792. + }
  793. </pre>
  794. <p>Let's make this editable.</p>
  795. <p>First we`ll add a UI. Using radio buttons we can make an 8x2
  796. array of tiles</p>
  797. <pre class="prettyprint showlinemods notranslate lang-html" translate="no">&lt;body&gt;
  798. &lt;canvas id="c"&gt;&lt;/canvas&gt;
  799. + &lt;div id="ui"&gt;
  800. + &lt;div class="tiles"&gt;
  801. + &lt;input type="radio" name="voxel" id="voxel1" value="1"&gt;&lt;label for="voxel1" style="background-position: -0% -0%"&gt;&lt;/label&gt;
  802. + &lt;input type="radio" name="voxel" id="voxel2" value="2"&gt;&lt;label for="voxel2" style="background-position: -100% -0%"&gt;&lt;/label&gt;
  803. + &lt;input type="radio" name="voxel" id="voxel3" value="3"&gt;&lt;label for="voxel3" style="background-position: -200% -0%"&gt;&lt;/label&gt;
  804. + &lt;input type="radio" name="voxel" id="voxel4" value="4"&gt;&lt;label for="voxel4" style="background-position: -300% -0%"&gt;&lt;/label&gt;
  805. + &lt;input type="radio" name="voxel" id="voxel5" value="5"&gt;&lt;label for="voxel5" style="background-position: -400% -0%"&gt;&lt;/label&gt;
  806. + &lt;input type="radio" name="voxel" id="voxel6" value="6"&gt;&lt;label for="voxel6" style="background-position: -500% -0%"&gt;&lt;/label&gt;
  807. + &lt;input type="radio" name="voxel" id="voxel7" value="7"&gt;&lt;label for="voxel7" style="background-position: -600% -0%"&gt;&lt;/label&gt;
  808. + &lt;input type="radio" name="voxel" id="voxel8" value="8"&gt;&lt;label for="voxel8" style="background-position: -700% -0%"&gt;&lt;/label&gt;
  809. + &lt;/div&gt;
  810. + &lt;div class="tiles"&gt;
  811. + &lt;input type="radio" name="voxel" id="voxel9" value="9" &gt;&lt;label for="voxel9" style="background-position: -800% -0%"&gt;&lt;/label&gt;
  812. + &lt;input type="radio" name="voxel" id="voxel10" value="10"&gt;&lt;label for="voxel10" style="background-position: -900% -0%"&gt;&lt;/label&gt;
  813. + &lt;input type="radio" name="voxel" id="voxel11" value="11"&gt;&lt;label for="voxel11" style="background-position: -1000% -0%"&gt;&lt;/label&gt;
  814. + &lt;input type="radio" name="voxel" id="voxel12" value="12"&gt;&lt;label for="voxel12" style="background-position: -1100% -0%"&gt;&lt;/label&gt;
  815. + &lt;input type="radio" name="voxel" id="voxel13" value="13"&gt;&lt;label for="voxel13" style="background-position: -1200% -0%"&gt;&lt;/label&gt;
  816. + &lt;input type="radio" name="voxel" id="voxel14" value="14"&gt;&lt;label for="voxel14" style="background-position: -1300% -0%"&gt;&lt;/label&gt;
  817. + &lt;input type="radio" name="voxel" id="voxel15" value="15"&gt;&lt;label for="voxel15" style="background-position: -1400% -0%"&gt;&lt;/label&gt;
  818. + &lt;input type="radio" name="voxel" id="voxel16" value="16"&gt;&lt;label for="voxel16" style="background-position: -1500% -0%"&gt;&lt;/label&gt;
  819. + &lt;/div&gt;
  820. + &lt;/div&gt;
  821. &lt;/body&gt;
  822. </pre>
  823. <p>And add some CSS to style it, display the tiles and highlight
  824. the current selection</p>
  825. <pre class="prettyprint showlinemods notranslate lang-css" translate="no">body {
  826. margin: 0;
  827. }
  828. #c {
  829. width: 100%;
  830. height: 100%;
  831. display: block;
  832. }
  833. +#ui {
  834. + position: absolute;
  835. + left: 10px;
  836. + top: 10px;
  837. + background: rgba(0, 0, 0, 0.8);
  838. + padding: 5px;
  839. +}
  840. +#ui input[type=radio] {
  841. + width: 0;
  842. + height: 0;
  843. + display: none;
  844. +}
  845. +#ui input[type=radio] + label {
  846. + background-image: url('resources/images/minecraft/flourish-cc-by-nc-sa.png');
  847. + background-size: 1600% 400%;
  848. + image-rendering: pixelated;
  849. + width: 64px;
  850. + height: 64px;
  851. + display: inline-block;
  852. +}
  853. +#ui input[type=radio]:checked + label {
  854. + outline: 3px solid red;
  855. +}
  856. +@media (max-width: 600px), (max-height: 600px) {
  857. + #ui input[type=radio] + label {
  858. + width: 32px;
  859. + height: 32px;
  860. + }
  861. +}
  862. </pre>
  863. <p>The UX will be as follows. If no tile is selected and you click a voxel that
  864. voxel will be erased or if you click a voxel and are holding the shift key it
  865. will be erased. Otherwise if a tiles is selected it will be added. You can
  866. deselect the selected tile type by clicking it again.</p>
  867. <p>This code will let the user unselect the highlighted
  868. radio button.</p>
  869. <pre class="prettyprint showlinemods notranslate lang-js" translate="no">let currentVoxel = 0;
  870. let currentId;
  871. document.querySelectorAll('#ui .tiles input[type=radio][name=voxel]').forEach((elem) =&gt; {
  872. elem.addEventListener('click', allowUncheck);
  873. });
  874. function allowUncheck() {
  875. if (this.id === currentId) {
  876. this.checked = false;
  877. currentId = undefined;
  878. currentVoxel = 0;
  879. } else {
  880. currentId = this.id;
  881. currentVoxel = parseInt(this.value);
  882. }
  883. }
  884. </pre>
  885. <p>And this below code will let us set a voxel based on where
  886. the user clicks. It uses code similar to the code we
  887. made in <a href="picking.html">the article on picking</a>
  888. but it's not using the built in <code class="notranslate" translate="no">RayCaster</code>. Instead
  889. it's using <code class="notranslate" translate="no">VoxelWorld.intersectRay</code> which returns
  890. the position of intersection and the normal of the face
  891. hit.</p>
  892. <pre class="prettyprint showlinemods notranslate lang-js" translate="no">function getCanvasRelativePosition(event) {
  893. const rect = canvas.getBoundingClientRect();
  894. return {
  895. x: (event.clientX - rect.left) * canvas.width / rect.width,
  896. y: (event.clientY - rect.top ) * canvas.height / rect.height,
  897. };
  898. }
  899. function placeVoxel(event) {
  900. const pos = getCanvasRelativePosition(event);
  901. const x = (pos.x / canvas.width ) * 2 - 1;
  902. const y = (pos.y / canvas.height) * -2 + 1; // note we flip Y
  903. const start = new THREE.Vector3();
  904. const end = new THREE.Vector3();
  905. start.setFromMatrixPosition(camera.matrixWorld);
  906. end.set(x, y, 1).unproject(camera);
  907. const intersection = world.intersectRay(start, end);
  908. if (intersection) {
  909. const voxelId = event.shiftKey ? 0 : currentVoxel;
  910. // the intersection point is on the face. That means
  911. // the math imprecision could put us on either side of the face.
  912. // so go half a normal into the voxel if removing (currentVoxel = 0)
  913. // our out of the voxel if adding (currentVoxel &gt; 0)
  914. const pos = intersection.position.map((v, ndx) =&gt; {
  915. return v + intersection.normal[ndx] * (voxelId &gt; 0 ? 0.5 : -0.5);
  916. });
  917. world.setVoxel(...pos, voxelId);
  918. updateVoxelGeometry(...pos);
  919. requestRenderIfNotRequested();
  920. }
  921. }
  922. const mouse = {
  923. x: 0,
  924. y: 0,
  925. };
  926. function recordStartPosition(event) {
  927. mouse.x = event.clientX;
  928. mouse.y = event.clientY;
  929. mouse.moveX = 0;
  930. mouse.moveY = 0;
  931. }
  932. function recordMovement(event) {
  933. mouse.moveX += Math.abs(mouse.x - event.clientX);
  934. mouse.moveY += Math.abs(mouse.y - event.clientY);
  935. }
  936. function placeVoxelIfNoMovement(event) {
  937. if (mouse.moveX &lt; 5 &amp;&amp; mouse.moveY &lt; 5) {
  938. placeVoxel(event);
  939. }
  940. window.removeEventListener('pointermove', recordMovement);
  941. window.removeEventListener('pointerup', placeVoxelIfNoMovement);
  942. }
  943. canvas.addEventListener('pointerdown', (event) =&gt; {
  944. event.preventDefault();
  945. recordStartPosition(event);
  946. window.addEventListener('pointermove', recordMovement);
  947. window.addEventListener('pointerup', placeVoxelIfNoMovement);
  948. }, {passive: false});
  949. canvas.addEventListener('touchstart', (event) =&gt; {
  950. // stop scrolling
  951. event.preventDefault();
  952. }, {passive: false});
  953. </pre>
  954. <p>There's a lot going on in the code above. Basically the mouse
  955. has a dual purpose. One is to move the camera. The other is to
  956. edit the world. Placing/Erasing a voxel happen when you let off the mouse
  957. but only if you have not moved the mouse since you first pressed down.
  958. This is just a guess that if you did move the mouse you were trying
  959. to move the camera, not place a block. <code class="notranslate" translate="no">moveX</code> and <code class="notranslate" translate="no">moveY</code> are
  960. in absolute movement so if you move to the left 10 and then back to
  961. the right 10 you'll have moved 20 units. In that case the user likely
  962. was just rotating the model back and forth and does not want to
  963. place a block. I didn't do any testing to see if <code class="notranslate" translate="no">5</code> is a good range or not. </p>
  964. <p>In the code we call <code class="notranslate" translate="no">world.setVoxel</code> to set a voxel and
  965. then <code class="notranslate" translate="no">updateVoxelGeometry</code> to update the three.js geometry
  966. based on what's changed.</p>
  967. <p>Let's make that now. If the user clicks a
  968. voxel on the edge of a cell then the geometry for the voxel
  969. in the adjacent cell might need new geometry. This means
  970. we need to check the cell for the voxel we just edited
  971. as well as in all 6 directions from that cell.</p>
  972. <pre class="prettyprint showlinemods notranslate lang-js" translate="no">const neighborOffsets = [
  973. [ 0, 0, 0], // self
  974. [-1, 0, 0], // left
  975. [ 1, 0, 0], // right
  976. [ 0, -1, 0], // down
  977. [ 0, 1, 0], // up
  978. [ 0, 0, -1], // back
  979. [ 0, 0, 1], // front
  980. ];
  981. function updateVoxelGeometry(x, y, z) {
  982. const updatedCellIds = {};
  983. for (const offset of neighborOffsets) {
  984. const ox = x + offset[0];
  985. const oy = y + offset[1];
  986. const oz = z + offset[2];
  987. const cellId = world.computeCellId(ox, oy, oz);
  988. if (!updatedCellIds[cellId]) {
  989. updatedCellIds[cellId] = true;
  990. updateCellGeometry(ox, oy, oz);
  991. }
  992. }
  993. }
  994. </pre>
  995. <p>I thought about checking for adjacent cells like </p>
  996. <pre class="prettyprint showlinemods notranslate lang-js" translate="no">const voxelX = THREE.MathUtils.euclideanModulo(x, cellSize) | 0;
  997. if (voxelX === 0) {
  998. // update cell to the left
  999. } else if (voxelX === cellSize - 1) {
  1000. // update cell to the right
  1001. }
  1002. </pre>
  1003. <p>and there would be 4 more checks for the other 4 directions
  1004. but it occurred to me the code would be much simpler with
  1005. just an array of offsets and saving off the cell ids of
  1006. the cells we already updated. If the updated voxel is not
  1007. on the edge of a cell then the test will quickly reject updating
  1008. the same cell.</p>
  1009. <p>For <code class="notranslate" translate="no">updateCellGeometry</code> we're just going to take the code we
  1010. had before that was generating the geometry for one cell
  1011. and make it handle multiple cells.</p>
  1012. <pre class="prettyprint showlinemods notranslate lang-js" translate="no">const cellIdToMesh = {};
  1013. function updateCellGeometry(x, y, z) {
  1014. const cellX = Math.floor(x / cellSize);
  1015. const cellY = Math.floor(y / cellSize);
  1016. const cellZ = Math.floor(z / cellSize);
  1017. const cellId = world.computeCellId(x, y, z);
  1018. let mesh = cellIdToMesh[cellId];
  1019. const geometry = mesh ? mesh.geometry : new THREE.BufferGeometry();
  1020. const {positions, normals, uvs, indices} = world.generateGeometryDataForCell(cellX, cellY, cellZ);
  1021. const positionNumComponents = 3;
  1022. geometry.setAttribute('position', new THREE.BufferAttribute(new Float32Array(positions), positionNumComponents));
  1023. const normalNumComponents = 3;
  1024. geometry.setAttribute('normal', new THREE.BufferAttribute(new Float32Array(normals), normalNumComponents));
  1025. const uvNumComponents = 2;
  1026. geometry.setAttribute('uv', new THREE.BufferAttribute(new Float32Array(uvs), uvNumComponents));
  1027. geometry.setIndex(indices);
  1028. geometry.computeBoundingSphere();
  1029. if (!mesh) {
  1030. mesh = new THREE.Mesh(geometry, material);
  1031. mesh.name = cellId;
  1032. cellIdToMesh[cellId] = mesh;
  1033. scene.add(mesh);
  1034. mesh.position.set(cellX * cellSize, cellY * cellSize, cellZ * cellSize);
  1035. }
  1036. }
  1037. </pre>
  1038. <p>The code above checks a map of cell ids to meshes. If
  1039. we ask for a cell that doesn't exist a new <a href="/docs/#api/en/objects/Mesh"><code class="notranslate" translate="no">Mesh</code></a> is made
  1040. and added to the correct place in world space.
  1041. At the end we update the attributes and indices with the new data.</p>
  1042. <p></p><div translate="no" class="threejs_example_container notranslate">
  1043. <div><iframe class="threejs_example notranslate" translate="no" style=" " src="/manual/examples/resources/editor.html?url=/manual/examples/voxel-geometry-culled-faces-ui.html"></iframe></div>
  1044. <a class="threejs_center" href="/manual/examples/voxel-geometry-culled-faces-ui.html" target="_blank">click here to open in a separate window</a>
  1045. </div>
  1046. <p></p>
  1047. <p>Some notes:</p>
  1048. <p><code class="notranslate" translate="no">RayCaster</code> might have worked just fine. I didn't try it.
  1049. Instead I found <a href="https://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.42.3443&rep=rep1&type=pdf">a voxel specific raycaster</a>.
  1050. that is optimized for voxels.</p>
  1051. <p>I made <code class="notranslate" translate="no">intersectRay</code> part of VoxelWorld because it seemed
  1052. like if it gets too slow we could raycast against cells
  1053. before raycasting on voxels as a simple speed up if it becomes
  1054. too slow.</p>
  1055. <p>You might want to change the length of the raycast
  1056. as currently it's all the way to Z-far. I expect if the
  1057. user clicks something too far way they don't really want
  1058. to be placing blocks on the other side of the world that
  1059. are 1 or 2 pixel large.</p>
  1060. <p>Calling <code class="notranslate" translate="no">geometry.computeBoundingSphere</code> might be slow.
  1061. We could just manually set the bounding sphere to the fit
  1062. the entire cell.</p>
  1063. <p>Do we want remove cells if all voxels in that cell are 0?
  1064. That would probably be reasonable change if we wanted to ship this.</p>
  1065. <p>Thinking about how this works it's clear the absolute
  1066. worst case is a checkerboard of on and off voxels. I don't
  1067. know off the top of my head what other strategies to use
  1068. if things get too slow. Maybe getting too slow would just
  1069. encourage the user not to make giant checkerboard areas.</p>
  1070. <p>To keep it simple the texture atlas is just 1 column
  1071. per voxel type. It would be better to make something more
  1072. flexible where we have a table of voxel types and each
  1073. type can specify where its face textures are in the atlas.
  1074. As it is lots of space is wasted.</p>
  1075. <p>Looking at real minecraft there are tiles that are not
  1076. voxels, not cubes. Like a fence tile or flowers. To do that
  1077. we'd again need some table of voxel types and for each
  1078. voxel whether it's a cube or some other geometry. If it's
  1079. not a cube the neighbor check when generating the geometry
  1080. would also need to change. A flower voxel next to another
  1081. voxel should not remove the faces between them.</p>
  1082. <p>If you want to make some minecraft like thing using three.js
  1083. I hope this has given you some ideas where to start and how
  1084. to generate some what efficient geometry.</p>
  1085. <p><canvas id="c"></canvas></p>
  1086. <script type="module" src="../resources/threejs-voxel-geometry.js"></script>
  1087. </div>
  1088. </div>
  1089. </div>
  1090. <script src="../resources/prettify.js"></script>
  1091. <script src="../resources/lesson.js"></script>
  1092. </body></html>