forked from michaljaz/webmc
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathChunkTerrain.js
More file actions
99 lines (86 loc) · 2.71 KB
/
ChunkTerrain.js
File metadata and controls
99 lines (86 loc) · 2.71 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
var modulo = function (a, b) {
return ((+a % (b = +b)) + b) % b;
};
class ChunkTerrain {
constructor(options) {
this.chunkSize = 16;
this.chunks = {};
this.blocksDef = options.blocksDef;
}
vecToStr(x, y, z) {
return `${parseInt(x)}:${parseInt(y)}:${parseInt(z)}`;
}
strToVec(str) {
str = str.split(":");
return [parseInt(str[0]), parseInt(str[1]), parseInt(str[2])];
}
computeVoxelOffset(voxelX, voxelY, voxelZ) {
var x = modulo(voxelX, this.chunkSize) | 0;
var y = modulo(voxelY, this.chunkSize) | 0;
var z = modulo(voxelZ, this.chunkSize) | 0;
return y * this.chunkSize * this.chunkSize + z * this.chunkSize + x;
}
computeChunkForVoxel(voxelX, voxelY, voxelZ) {
return [
Math.floor(voxelX / this.chunkSize),
Math.floor(voxelY / this.chunkSize),
Math.floor(voxelZ / this.chunkSize),
];
}
addChunkForVoxel(voxelX, voxelY, voxelZ) {
var cellId = this.vecToStr(
...this.computeChunkForVoxel(voxelX, voxelY, voxelZ)
);
var cell = this.chunks[cellId];
if (!cell) {
cell = new Uint32Array(
this.chunkSize * this.chunkSize * this.chunkSize
);
this.chunks[cellId] = cell;
}
return cell;
}
getChunkForVoxel(voxelX, voxelY, voxelZ) {
var cellId = this.vecToStr(
...this.computeChunkForVoxel(voxelX, voxelY, voxelZ)
);
return this.chunks[cellId];
}
setVoxel(voxelX, voxelY, voxelZ, value) {
var cell = this.getChunkForVoxel(voxelX, voxelY, voxelZ);
if (!cell) {
cell = this.addChunkForVoxel(voxelX, voxelY, voxelZ);
}
var voff = this.computeVoxelOffset(voxelX, voxelY, voxelZ);
cell[voff] = value;
}
getVoxel(voxelX, voxelY, voxelZ) {
var cell = this.getChunkForVoxel(voxelX, voxelY, voxelZ);
if (!cell) {
return 0;
}
var voff = this.computeVoxelOffset(voxelX, voxelY, voxelZ);
return cell[voff];
}
setChunk(chunkX, chunkY, chunkZ, buffer) {
this.chunks[this.vecToStr(chunkX, chunkY, chunkZ)] = buffer;
}
getBlock(blockX, blockY, blockZ) {
var stateId = this.getVoxel(blockX, blockY, blockZ);
var def = this.blocksDef[stateId];
if (def !== void 0) {
return {
name: def[0],
stateId,
boundingBox: def[1] === 1 ? "block" : "empty",
transparent: def[2],
};
} else {
return false;
}
}
reset() {
this.chunks = {};
}
}
export { ChunkTerrain };