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

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