voxel-geometry-culled-faces-with-textures.html 9.2 KB

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