forked from Minestom/Minestom
-
-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathDynamicChunk.java
More file actions
342 lines (293 loc) · 12.8 KB
/
DynamicChunk.java
File metadata and controls
342 lines (293 loc) · 12.8 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
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
package net.minestom.server.instance;
import it.unimi.dsi.fastutil.ints.Int2ObjectOpenHashMap;
import net.kyori.adventure.nbt.CompoundBinaryTag;
import net.kyori.adventure.nbt.LongArrayBinaryTag;
import net.minestom.server.MinecraftServer;
import net.minestom.server.coordinate.Point;
import net.minestom.server.coordinate.Vec;
import net.minestom.server.entity.Entity;
import net.minestom.server.instance.block.Block;
import net.minestom.server.instance.block.BlockHandler;
import net.minestom.server.instance.heightmap.Heightmap;
import net.minestom.server.instance.heightmap.MotionBlockingHeightmap;
import net.minestom.server.instance.heightmap.WorldSurfaceHeightmap;
import net.minestom.server.network.NetworkBuffer;
import net.minestom.server.network.packet.server.CachedPacket;
import net.minestom.server.network.packet.server.SendablePacket;
import net.minestom.server.network.packet.server.play.ChunkDataPacket;
import net.minestom.server.network.packet.server.play.UpdateLightPacket;
import net.minestom.server.network.packet.server.play.data.ChunkData;
import net.minestom.server.network.packet.server.play.data.LightData;
import net.minestom.server.registry.DynamicRegistry;
import net.minestom.server.snapshot.ChunkSnapshot;
import net.minestom.server.snapshot.SnapshotImpl;
import net.minestom.server.snapshot.SnapshotUpdater;
import net.minestom.server.utils.ArrayUtils;
import net.minestom.server.utils.chunk.ChunkUtils;
import net.minestom.server.utils.validate.Check;
import net.minestom.server.world.DimensionType;
import net.minestom.server.world.biome.Biome;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.*;
import static net.minestom.server.utils.chunk.ChunkUtils.toSectionRelativeCoordinate;
/**
* Represents a {@link Chunk} which store each individual block in memory.
* <p>
* WARNING: not thread-safe.
*/
public class DynamicChunk extends Chunk {
private static final Logger LOGGER = LoggerFactory.getLogger(DynamicChunk.class);
protected List<Section> sections;
private boolean needsCompleteHeightmapRefresh = true;
protected Heightmap motionBlocking = new MotionBlockingHeightmap(this);
protected Heightmap worldSurface = new WorldSurfaceHeightmap(this);
// Key = ChunkUtils#getBlockIndex
protected final Int2ObjectOpenHashMap<Block> entries = new Int2ObjectOpenHashMap<>(0);
protected final Int2ObjectOpenHashMap<Block> tickableMap = new Int2ObjectOpenHashMap<>(0);
private long lastChange;
final CachedPacket chunkCache = new CachedPacket(this::createChunkPacket);
private static final DynamicRegistry<Biome> BIOME_REGISTRY = MinecraftServer.getBiomeRegistry();
public DynamicChunk(@NotNull Instance instance, int chunkX, int chunkZ) {
super(instance, chunkX, chunkZ, true);
var sectionsTemp = new Section[maxSection - minSection];
Arrays.setAll(sectionsTemp, value -> new Section());
this.sections = List.of(sectionsTemp);
}
@Override
public void setBlock(int x, int y, int z, @NotNull Block block,
@Nullable BlockHandler.Placement placement,
@Nullable BlockHandler.Destroy destroy) {
final DimensionType instanceDim = instance.getCachedDimensionType();
if (y >= instanceDim.maxY() || y < instanceDim.minY()) {
LOGGER.warn("tried to set a block outside the world bounds, should be within [{}, {}): {}",
instanceDim.minY(), instanceDim.maxY(), y);
return;
}
assertLock();
this.lastChange = System.currentTimeMillis();
this.chunkCache.invalidate();
Section section = getSectionAt(y);
int sectionRelativeX = toSectionRelativeCoordinate(x);
int sectionRelativeZ = toSectionRelativeCoordinate(z);
section.blockPalette().set(
sectionRelativeX,
toSectionRelativeCoordinate(y),
sectionRelativeZ,
block.stateId()
);
final int index = ChunkUtils.getBlockIndex(x, y, z);
// Handler
final BlockHandler handler = block.handler();
final Block lastCachedBlock;
if (handler != null || block.hasNbt() || block.registry().isBlockEntity()) {
lastCachedBlock = this.entries.put(index, block);
} else {
lastCachedBlock = this.entries.remove(index);
}
// Block tick
if (handler != null && handler.isTickable()) {
this.tickableMap.put(index, block);
} else {
this.tickableMap.remove(index);
}
// Update block handlers
var blockPosition = new Vec(x, y, z);
if (lastCachedBlock != null && lastCachedBlock.handler() != null) {
// Previous destroy
lastCachedBlock.handler().onDestroy(Objects.requireNonNullElseGet(destroy,
() -> new BlockHandler.Destroy(lastCachedBlock, instance, blockPosition)));
}
if (handler != null) {
// New placement
final Block finalBlock = block;
handler.onPlace(Objects.requireNonNullElseGet(placement,
() -> new BlockHandler.Placement(finalBlock, instance, blockPosition)));
}
// UpdateHeightMaps
if (needsCompleteHeightmapRefresh) calculateFullHeightmap();
motionBlocking.refresh(sectionRelativeX, y, sectionRelativeZ, block);
worldSurface.refresh(sectionRelativeX, y, sectionRelativeZ, block);
}
@Override
public void setBiome(int x, int y, int z, @NotNull DynamicRegistry.Key<Biome> biome) {
assertLock();
this.chunkCache.invalidate();
Section section = getSectionAt(y);
var id = BIOME_REGISTRY.getId(biome.namespace());
if (id == -1) throw new IllegalStateException("Biome has not been registered: " + biome.namespace());
section.biomePalette().set(
toSectionRelativeCoordinate(x) / 4,
toSectionRelativeCoordinate(y) / 4,
toSectionRelativeCoordinate(z) / 4, id);
}
@Override
public @NotNull List<Section> getSections() {
return sections;
}
@Override
public @NotNull Section getSection(int section) {
return sections.get(section - minSection);
}
@Override
public @NotNull Heightmap motionBlockingHeightmap() {
return motionBlocking;
}
@Override
public @NotNull Heightmap worldSurfaceHeightmap() {
return worldSurface;
}
@Override
public void loadHeightmapsFromNBT(CompoundBinaryTag heightmapsNBT) {
if (heightmapsNBT.get(motionBlockingHeightmap().NBTName()) instanceof LongArrayBinaryTag array) {
motionBlockingHeightmap().loadFrom(array.value());
}
if (heightmapsNBT.get(worldSurfaceHeightmap().NBTName()) instanceof LongArrayBinaryTag array) {
worldSurfaceHeightmap().loadFrom(array.value());
}
}
@Override
public void tick(long time) {
if (tickableMap.isEmpty()) return;
tickableMap.int2ObjectEntrySet().fastForEach(entry -> {
final int index = entry.getIntKey();
final Block block = entry.getValue();
final BlockHandler handler = block.handler();
if (handler == null) return;
final Point blockPosition = ChunkUtils.getBlockPosition(index, chunkX, chunkZ);
handler.tick(new BlockHandler.Tick(block, instance, blockPosition));
});
}
@Override
public @Nullable Block getBlock(int x, int y, int z, @NotNull Condition condition) {
assertLock();
if (y < minSection * CHUNK_SECTION_SIZE || y >= maxSection * CHUNK_SECTION_SIZE)
return Block.AIR; // Out of bounds
// Verify if the block object is present
if (condition != Condition.TYPE) {
final Block entry = !entries.isEmpty() ?
entries.get(ChunkUtils.getBlockIndex(x, y, z)) : null;
if (entry != null || condition == Condition.CACHED) {
return entry;
}
}
// Retrieve the block from state id
final Section section = getSectionAt(y);
final int blockStateId = section.blockPalette()
.get(toSectionRelativeCoordinate(x), toSectionRelativeCoordinate(y), toSectionRelativeCoordinate(z));
return Objects.requireNonNullElse(Block.fromStateId((short) blockStateId), Block.AIR);
}
@Override
public @NotNull DynamicRegistry.Key<Biome> getBiome(int x, int y, int z) {
assertLock();
final Section section = getSectionAt(y);
final int id = section.biomePalette()
.get(toSectionRelativeCoordinate(x) / 4, toSectionRelativeCoordinate(y) / 4, toSectionRelativeCoordinate(z) / 4);
DynamicRegistry.Key<Biome> biome = BIOME_REGISTRY.getKey(id);
Check.notNull(biome, "Biome with id {0} is not registered", id);
return biome;
}
@Override
public long getLastChangeTime() {
return lastChange;
}
@Override
public @NotNull SendablePacket getFullDataPacket() {
return chunkCache;
}
@Override
public @NotNull Chunk copy(@NotNull Instance instance, int chunkX, int chunkZ) {
DynamicChunk dynamicChunk = new DynamicChunk(instance, chunkX, chunkZ);
dynamicChunk.sections = sections.stream().map(Section::clone).toList();
dynamicChunk.entries.putAll(entries);
return dynamicChunk;
}
@Override
public void reset() {
for (Section section : sections) section.clear();
this.entries.clear();
}
@Override
public void invalidate() {
this.chunkCache.invalidate();
}
private @NotNull ChunkDataPacket createChunkPacket() {
final byte[] data;
final CompoundBinaryTag heightmapsNBT;
synchronized (this) {
heightmapsNBT = getHeightmapNBT();
data = NetworkBuffer.makeArray(networkBuffer -> {
for (Section section : sections) networkBuffer.write(section);
});
}
return new ChunkDataPacket(chunkX, chunkZ,
new ChunkData(heightmapsNBT, data, entries),
createLightData(true)
);
}
@NotNull UpdateLightPacket createLightPacket() {
return new UpdateLightPacket(chunkX, chunkZ, createLightData(false));
}
protected LightData createLightData(boolean requiredFullChunk) {
BitSet skyMask = new BitSet();
BitSet blockMask = new BitSet();
BitSet emptySkyMask = new BitSet();
BitSet emptyBlockMask = new BitSet();
List<byte[]> skyLights = new ArrayList<>();
List<byte[]> blockLights = new ArrayList<>();
int index = 0;
for (Section section : sections) {
index++;
final byte[] skyLight = section.skyLight().array();
final byte[] blockLight = section.blockLight().array();
if (skyLight.length != 0) {
skyLights.add(skyLight);
skyMask.set(index);
} else {
emptySkyMask.set(index);
}
if (blockLight.length != 0) {
blockLights.add(blockLight);
blockMask.set(index);
} else {
emptyBlockMask.set(index);
}
}
return new LightData(
skyMask, blockMask,
emptySkyMask, emptyBlockMask,
skyLights, blockLights
);
}
protected CompoundBinaryTag getHeightmapNBT() {
if (needsCompleteHeightmapRefresh) calculateFullHeightmap();
return CompoundBinaryTag.builder()
.putLongArray(motionBlocking.NBTName(), motionBlocking.getNBT())
.putLongArray(worldSurface.NBTName(), worldSurface.getNBT())
.build();
}
private void calculateFullHeightmap() {
int startY = Heightmap.getHighestBlockSection(this);
motionBlocking.refresh(startY);
worldSurface.refresh(startY);
needsCompleteHeightmapRefresh = false;
}
@Override
public @NotNull ChunkSnapshot updateSnapshot(@NotNull SnapshotUpdater updater) {
Section[] clonedSections = new Section[sections.size()];
for (int i = 0; i < clonedSections.length; i++)
clonedSections[i] = sections.get(i).clone();
var entities = instance.getEntityTracker().chunkEntities(chunkX, chunkZ, EntityTracker.Target.ENTITIES);
final int[] entityIds = ArrayUtils.mapToIntArray(entities, Entity::getEntityId);
return new SnapshotImpl.Chunk(minSection, chunkX, chunkZ,
clonedSections, entries.clone(), entityIds, updater.reference(instance),
tagHandler().readableCopy());
}
private void assertLock() {
if (!Thread.holdsLock(this)) {
throw new IllegalStateException("Chunk must be locked before access");
}
}
}