threejs-voxel-geometry-culled-faces-with-textures.html 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316
  1. <!-- Licensed under a BSD license. See license.html for license -->
  2. <!DOCTYPE html>
  3. <html>
  4. <head>
  5. <meta charset="utf-8">
  6. <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=yes">
  7. <title>Three.js - Voxel Geometry - Textures</title>
  8. <style>
  9. body {
  10. margin: 0;
  11. }
  12. #c {
  13. width: 100vw;
  14. height: 100vh;
  15. display: block;
  16. }
  17. </style>
  18. </head>
  19. <body>
  20. <canvas id="c"></canvas>
  21. </body>
  22. <script type="module">
  23. import * as THREE from './resources/threejs/r110/build/three.module.js';
  24. import {OrbitControls} from './resources/threejs/r110/examples/jsm/controls/OrbitControls.js';
  25. class VoxelWorld {
  26. constructor(options) {
  27. this.cellSize = options.cellSize;
  28. this.tileSize = options.tileSize;
  29. this.tileTextureWidth = options.tileTextureWidth;
  30. this.tileTextureHeight = options.tileTextureHeight;
  31. const {cellSize} = this;
  32. this.cellSliceSize = cellSize * cellSize;
  33. this.cell = new Uint8Array(cellSize * cellSize * cellSize);
  34. }
  35. computeVoxelOffset(x, y, z) {
  36. const {cellSize, cellSliceSize} = this;
  37. const voxelX = THREE.Math.euclideanModulo(x, cellSize) | 0;
  38. const voxelY = THREE.Math.euclideanModulo(y, cellSize) | 0;
  39. const voxelZ = THREE.Math.euclideanModulo(z, cellSize) | 0;
  40. return voxelY * cellSliceSize +
  41. voxelZ * cellSize +
  42. voxelX;
  43. }
  44. getCellForVoxel(x, y, z) {
  45. const {cellSize} = this;
  46. const cellX = Math.floor(x / cellSize);
  47. const cellY = Math.floor(y / cellSize);
  48. const cellZ = Math.floor(z / cellSize);
  49. if (cellX !== 0 || cellY !== 0 || cellZ !== 0) {
  50. return null;
  51. }
  52. return this.cell;
  53. }
  54. setVoxel(x, y, z, v) {
  55. const cell = this.getCellForVoxel(x, y, z);
  56. if (!cell) {
  57. return; // TODO: add a new cell?
  58. }
  59. const voxelOffset = this.computeVoxelOffset(x, y, z);
  60. cell[voxelOffset] = v;
  61. }
  62. getVoxel(x, y, z) {
  63. const cell = this.getCellForVoxel(x, y, z);
  64. if (!cell) {
  65. return 0;
  66. }
  67. const voxelOffset = this.computeVoxelOffset(x, y, z);
  68. return cell[voxelOffset];
  69. }
  70. generateGeometryDataForCell(cellX, cellY, cellZ) {
  71. const {cellSize, tileSize, tileTextureWidth, tileTextureHeight} = this;
  72. const positions = [];
  73. const normals = [];
  74. const uvs = [];
  75. const indices = [];
  76. const startX = cellX * cellSize;
  77. const startY = cellY * cellSize;
  78. const startZ = cellZ * cellSize;
  79. for (let y = 0; y < cellSize; ++y) {
  80. const voxelY = startY + y;
  81. for (let z = 0; z < cellSize; ++z) {
  82. const voxelZ = startZ + z;
  83. for (let x = 0; x < cellSize; ++x) {
  84. const voxelX = startX + x;
  85. const voxel = this.getVoxel(voxelX, voxelY, voxelZ);
  86. if (voxel) {
  87. // voxel 0 is sky (empty) so for UVs we start at 0
  88. const uvVoxel = voxel - 1;
  89. // There is a voxel here but do we need faces for it?
  90. for (const {dir, corners, uvRow} of VoxelWorld.faces) {
  91. const neighbor = this.getVoxel(
  92. voxelX + dir[0],
  93. voxelY + dir[1],
  94. voxelZ + dir[2]);
  95. if (!neighbor) {
  96. // this voxel has no neighbor in this direction so we need a face.
  97. const ndx = positions.length / 3;
  98. for (const {pos, uv} of corners) {
  99. positions.push(pos[0] + x, pos[1] + y, pos[2] + z);
  100. normals.push(...dir);
  101. uvs.push(
  102. (uvVoxel + uv[0]) * tileSize / tileTextureWidth,
  103. 1 - (uvRow + 1 - uv[1]) * tileSize / tileTextureHeight);
  104. }
  105. indices.push(
  106. ndx, ndx + 1, ndx + 2,
  107. ndx + 2, ndx + 1, ndx + 3,
  108. );
  109. }
  110. }
  111. }
  112. }
  113. }
  114. }
  115. return {
  116. positions,
  117. normals,
  118. uvs,
  119. indices,
  120. };
  121. }
  122. }
  123. VoxelWorld.faces = [
  124. { // left
  125. uvRow: 0,
  126. dir: [ -1, 0, 0, ],
  127. corners: [
  128. { pos: [ 0, 1, 0 ], uv: [ 0, 1 ], },
  129. { pos: [ 0, 0, 0 ], uv: [ 0, 0 ], },
  130. { pos: [ 0, 1, 1 ], uv: [ 1, 1 ], },
  131. { pos: [ 0, 0, 1 ], uv: [ 1, 0 ], },
  132. ],
  133. },
  134. { // right
  135. uvRow: 0,
  136. dir: [ 1, 0, 0, ],
  137. corners: [
  138. { pos: [ 1, 1, 1 ], uv: [ 0, 1 ], },
  139. { pos: [ 1, 0, 1 ], uv: [ 0, 0 ], },
  140. { pos: [ 1, 1, 0 ], uv: [ 1, 1 ], },
  141. { pos: [ 1, 0, 0 ], uv: [ 1, 0 ], },
  142. ],
  143. },
  144. { // bottom
  145. uvRow: 1,
  146. dir: [ 0, -1, 0, ],
  147. corners: [
  148. { pos: [ 1, 0, 1 ], uv: [ 1, 0 ], },
  149. { pos: [ 0, 0, 1 ], uv: [ 0, 0 ], },
  150. { pos: [ 1, 0, 0 ], uv: [ 1, 1 ], },
  151. { pos: [ 0, 0, 0 ], uv: [ 0, 1 ], },
  152. ],
  153. },
  154. { // top
  155. uvRow: 2,
  156. dir: [ 0, 1, 0, ],
  157. corners: [
  158. { pos: [ 0, 1, 1 ], uv: [ 1, 1 ], },
  159. { pos: [ 1, 1, 1 ], uv: [ 0, 1 ], },
  160. { pos: [ 0, 1, 0 ], uv: [ 1, 0 ], },
  161. { pos: [ 1, 1, 0 ], uv: [ 0, 0 ], },
  162. ],
  163. },
  164. { // back
  165. uvRow: 0,
  166. dir: [ 0, 0, -1, ],
  167. corners: [
  168. { pos: [ 1, 0, 0 ], uv: [ 0, 0 ], },
  169. { pos: [ 0, 0, 0 ], uv: [ 1, 0 ], },
  170. { pos: [ 1, 1, 0 ], uv: [ 0, 1 ], },
  171. { pos: [ 0, 1, 0 ], uv: [ 1, 1 ], },
  172. ],
  173. },
  174. { // front
  175. uvRow: 0,
  176. dir: [ 0, 0, 1, ],
  177. corners: [
  178. { pos: [ 0, 0, 1 ], uv: [ 0, 0 ], },
  179. { pos: [ 1, 0, 1 ], uv: [ 1, 0 ], },
  180. { pos: [ 0, 1, 1 ], uv: [ 0, 1 ], },
  181. { pos: [ 1, 1, 1 ], uv: [ 1, 1 ], },
  182. ],
  183. },
  184. ];
  185. function main() {
  186. const canvas = document.querySelector('#c');
  187. const renderer = new THREE.WebGLRenderer({canvas});
  188. const cellSize = 32;
  189. const fov = 75;
  190. const aspect = 2; // the canvas default
  191. const near = 0.1;
  192. const far = 1000;
  193. const camera = new THREE.PerspectiveCamera(fov, aspect, near, far);
  194. camera.position.set(-cellSize * .3, cellSize * .8, -cellSize * .3);
  195. const controls = new OrbitControls(camera, canvas);
  196. controls.target.set(cellSize / 2, cellSize / 3, cellSize / 2);
  197. controls.update();
  198. const scene = new THREE.Scene();
  199. scene.background = new THREE.Color('lightblue');
  200. function addLight(x, y, z) {
  201. const color = 0xFFFFFF;
  202. const intensity = 1;
  203. const light = new THREE.DirectionalLight(color, intensity);
  204. light.position.set(x, y, z);
  205. scene.add(light);
  206. }
  207. addLight(-1, 2, 4);
  208. addLight( 1, -1, -2);
  209. const loader = new THREE.TextureLoader();
  210. const texture = loader.load('resources/images/minecraft/flourish-cc-by-nc-sa.png', render);
  211. texture.magFilter = THREE.NearestFilter;
  212. texture.minFilter = THREE.NearestFilter;
  213. const tileSize = 16;
  214. const tileTextureWidth = 256;
  215. const tileTextureHeight = 64;
  216. const world = new VoxelWorld({
  217. cellSize,
  218. tileSize,
  219. tileTextureWidth,
  220. tileTextureHeight,
  221. });
  222. for (let y = 0; y < cellSize; ++y) {
  223. for (let z = 0; z < cellSize; ++z) {
  224. for (let x = 0; x < cellSize; ++x) {
  225. const height = (Math.sin(x / cellSize * Math.PI * 2) + Math.sin(z / cellSize * Math.PI * 3)) * (cellSize / 6) + (cellSize / 2);
  226. if (y < height) {
  227. world.setVoxel(x, y, z, randInt(1, 17));
  228. }
  229. }
  230. }
  231. }
  232. function randInt(min, max) {
  233. return Math.floor(Math.random() * (max - min) + min);
  234. }
  235. const {positions, normals, uvs, indices} = world.generateGeometryDataForCell(0, 0, 0);
  236. const geometry = new THREE.BufferGeometry();
  237. const material = new THREE.MeshLambertMaterial({
  238. map: texture,
  239. side: THREE.DoubleSide,
  240. alphaTest: 0.1,
  241. transparent: true,
  242. });
  243. const positionNumComponents = 3;
  244. const normalNumComponents = 3;
  245. const uvNumComponents = 2;
  246. geometry.setAttribute(
  247. 'position',
  248. new THREE.BufferAttribute(new Float32Array(positions), positionNumComponents));
  249. geometry.setAttribute(
  250. 'normal',
  251. new THREE.BufferAttribute(new Float32Array(normals), normalNumComponents));
  252. geometry.setAttribute(
  253. 'uv',
  254. new THREE.BufferAttribute(new Float32Array(uvs), uvNumComponents));
  255. geometry.setIndex(indices);
  256. const mesh = new THREE.Mesh(geometry, material);
  257. scene.add(mesh);
  258. function resizeRendererToDisplaySize(renderer) {
  259. const canvas = renderer.domElement;
  260. const width = canvas.clientWidth;
  261. const height = canvas.clientHeight;
  262. const needResize = canvas.width !== width || canvas.height !== height;
  263. if (needResize) {
  264. renderer.setSize(width, height, false);
  265. }
  266. return needResize;
  267. }
  268. let renderRequested = false;
  269. function render() {
  270. renderRequested = undefined;
  271. if (resizeRendererToDisplaySize(renderer)) {
  272. const canvas = renderer.domElement;
  273. camera.aspect = canvas.clientWidth / canvas.clientHeight;
  274. camera.updateProjectionMatrix();
  275. }
  276. controls.update();
  277. renderer.render(scene, camera);
  278. }
  279. render();
  280. function requestRenderIfNotRequested() {
  281. if (!renderRequested) {
  282. renderRequested = true;
  283. requestAnimationFrame(render);
  284. }
  285. }
  286. controls.addEventListener('change', requestRenderIfNotRequested);
  287. window.addEventListener('resize', requestRenderIfNotRequested);
  288. }
  289. main();
  290. </script>
  291. </html>